Metadata-Version: 2.4
Name: rawr-tools
Version: 0.1.7
Summary: RAWR: Risk And Win Ratio — AI Quant Trading Tool for Korean Stock Market
Project-URL: Homepage, https://github.com/snowjang24/rawr-tools
Project-URL: Repository, https://github.com/snowjang24/rawr-tools
Project-URL: Documentation, https://github.com/snowjang24/rawr-tools#readme
Project-URL: Issues, https://github.com/snowjang24/rawr-tools/issues
Project-URL: Changelog, https://github.com/snowjang24/rawr-tools/blob/main/CHANGELOG.md
Author: Soonho Jang
License: Apache License
        Version 2.0, January 2004
        http://www.apache.org/licenses/
        
        TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
        1. Definitions.
        
        "License" shall mean the terms and conditions for use, reproduction, and
        distribution as defined by Sections 1 through 9 of this document.
        
        "Licensor" shall mean the copyright owner or entity authorized by the copyright
        owner that is granting the License.
        
        "Legal Entity" shall mean the union of the acting entity and all other entities
        that control, are controlled by, or are under common control with that entity.
        For the purposes of this definition, "control" means (i) the power, direct or
        indirect, to cause the direction or management of such entity, whether by
        contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
        outstanding shares, or (iii) beneficial ownership of such entity.
        
        "You" (or "Your") shall mean an individual or Legal Entity exercising
        permissions granted by this License.
        
        "Source" form shall mean the preferred form for making modifications, including
        but not limited to software source code, documentation source, and configuration
        files.
        
        "Object" form shall mean any form resulting from mechanical transformation or
        translation of a Source form, including but not limited to compiled object code,
        generated documentation, and conversions to other media types.
        
        "Work" shall mean the work of authorship, whether in Source or Object form, made
        available under the License, as indicated by a copyright notice that is included
        in or attached to the work (an example is provided in the Appendix below).
        
        "Derivative Works" shall mean any work, whether in Source or Object form, that
        is based on (or derived from) the Work and for which the editorial revisions,
        annotations, elaborations, or other modifications represent, as a whole, an
        original work of authorship. For the purposes of this License, Derivative Works
        shall not include works that remain separable from, or merely link (or bind by
        name) to the interfaces of, the Work and Derivative Works thereof.
        
        "Contribution" shall mean any work of authorship, including the original version
        of the Work and any modifications or additions to that Work or Derivative Works
        thereof, that is intentionally submitted to Licensor for inclusion in the Work
        by the copyright owner or by an individual or Legal Entity authorized to submit
        on behalf of the copyright owner. For the purposes of this definition,
        "submitted" means any form of electronic, verbal, or written communication sent
        to the Licensor or its representatives, including but not limited to
        communication on electronic mailing lists, source code control systems, and
        issue tracking systems that are managed by, or on behalf of, the Licensor for
        the purpose of discussing and improving the Work, but excluding communication
        that is conspicuously marked or otherwise designated in writing by the copyright
        owner as "Not a Contribution."
        
        "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
        of whom a Contribution has been received by Licensor and subsequently
        incorporated within the Work.
        
        2. Grant of Copyright License. Subject to the terms and conditions of this
        License, each Contributor hereby grants to You a perpetual, worldwide,
        non-exclusive, no-charge, royalty-free, irrevocable copyright license to
        reproduce, prepare Derivative Works of, publicly display, publicly perform,
        sublicense, and distribute the Work and such Derivative Works in Source or
        Object form.
        
        3. Grant of Patent License. Subject to the terms and conditions of this License,
        each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
        no-charge, royalty-free, irrevocable (except as stated in this section) patent
        license to make, have made, use, offer to sell, sell, import, and otherwise
        transfer the Work, where such license applies only to those patent claims
        licensable by such Contributor that are necessarily infringed by their
        Contribution(s) alone or by combination of their Contribution(s) with the Work
        to which such Contribution(s) was submitted. If You institute patent litigation
        against any entity (including a cross-claim or counterclaim in a lawsuit)
        alleging that the Work or a Contribution incorporated within the Work
        constitutes direct or contributory patent infringement, then any patent licenses
        granted to You under this License for that Work shall terminate as of the date
        such litigation is filed.
        
        4. Redistribution. You may reproduce and distribute copies of the Work or
        Derivative Works thereof in any medium, with or without modifications, and in
        Source or Object form, provided that You meet the following conditions:
        
        (a) You must give any other recipients of the Work or Derivative Works a copy of
        this License; and
        
        (b) You must cause any modified files to carry prominent notices stating that You
        changed the files; and
        
        (c) You must retain, in the Source form of any Derivative Works that You
        distribute, all copyright, patent, trademark, and attribution notices from the
        Source form of the Work, excluding those notices that do not pertain to any part
        of the Derivative Works; and
        
        (d) If the Work includes a "NOTICE" text file as part of its distribution, then
        any Derivative Works that You distribute must include a readable copy of the
        attribution notices contained within such NOTICE file, excluding those notices
        that do not pertain to any part of the Derivative Works, in at least one of the
        following places: within a NOTICE text file distributed as part of the
        Derivative Works; within the Source form or documentation, if provided along
        with the Derivative Works; or, within a display generated by the Derivative
        Works, if and wherever such third-party notices normally appear. The contents of
        the NOTICE file are for informational purposes only and do not modify the
        License. You may add Your own attribution notices within Derivative Works that
        You distribute, alongside or as an addendum to the NOTICE text from the Work,
        provided that such additional attribution notices cannot be construed as
        modifying the License.
        
        You may add Your own copyright statement to Your modifications and may provide
        additional or different license terms and conditions for use, reproduction, or
        distribution of Your modifications, or for any such Derivative Works as a whole,
        provided Your use, reproduction, and distribution of the Work otherwise complies
        with the conditions stated in this License.
        
        5. Submission of Contributions. Unless You explicitly state otherwise, any
        Contribution intentionally submitted for inclusion in the Work by You to the
        Licensor shall be under the terms and conditions of this License, without any
        additional terms or conditions. Notwithstanding the above, nothing herein shall
        supersede or modify the terms of any separate license agreement you may have
        executed with Licensor regarding such Contributions.
        
        6. Trademarks. This License does not grant permission to use the trade names,
        trademarks, service marks, or product names of the Licensor, except as required
        for reasonable and customary use in describing the origin of the Work and
        reproducing the content of the NOTICE file.
        
        7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
        writing, Licensor provides the Work (and each Contributor provides its
        Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
        KIND, either express or implied, including, without limitation, any warranties
        or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        PARTICULAR PURPOSE. You are solely responsible for determining the
        appropriateness of using or redistributing the Work and assume any risks
        associated with Your exercise of permissions under this License.
        
        8. Limitation of Liability. In no event and under no legal theory, whether in
        tor t (including negligence), contract, or otherwise, unless required by
        applicable law (such as deliberate and grossly negligent acts) or agreed to in
        writing, shall any Contributor be liable to You for damages, including any
        direct, indirect, special, incidental, or consequential damages of any character
        arising as a result of this License or out of the use or inability to use the
        Work (including but not limited to damages for loss of goodwill, work stoppage,
        computer failure or malfunction, or any and all other commercial damages or
        losses), even if such Contributor has been advised of the possibility of such
        damages.
        
        9. Accepting Warranty or Additional Liability. While redistributing the Work or
        Derivative Works thereof, You may choose to offer, and charge a fee for,
        acceptance of support, warranty, indemnity, or other liability obligations
        and/or rights consistent with this License. However, in accepting such
        obligations, You may act only on Your own behalf and on Your sole
        responsibility, not on behalf of any other Contributor, and only if You agree to
        indemnify, defend, and hold each Contributor harmless for any liability incurred
        by, or claims asserted against, such Contributor by reason of your accepting any
        such warranty or additional liability.
        
        END OF TERMS AND CONDITIONS
        
        APPENDIX: How to apply the Apache License to your work.
        
        To apply the Apache License to your work, attach the following boilerplate
        notice, with the fields enclosed by brackets "[]" replaced with your own
        identifying information. (Don't include the brackets!) The text should be
        enclosed in the appropriate comment syntax for the file format. We also
        recommend that a file or class name and description of purpose be included on the
        same "printed page" as the copyright notice for easier identification within
        third-party archives.
        
        Copyright [yyyy] [name of copyright owner]
        
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
        
            http://www.apache.org/licenses/LICENSE-2.0
        
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
License-File: LICENSE
Keywords: cli,korea,mcp,quant,stocks,trading
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Office/Business :: Financial :: Investment
Requires-Python: >=3.12
Requires-Dist: click>=8.0
Requires-Dist: pydantic>=2.0
Requires-Dist: tenacity>=9.0
Provides-Extra: dev
Requires-Dist: anthropic>=0.40; extra == 'dev'
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: fastmcp>=2.0; extra == 'dev'
Requires-Dist: finance-datareader>=0.9; extra == 'dev'
Requires-Dist: hatchling>=1.27; extra == 'dev'
Requires-Dist: httpx>=0.27; extra == 'dev'
Requires-Dist: keyring>=25.0; extra == 'dev'
Requires-Dist: numpy>=1.26; extra == 'dev'
Requires-Dist: openai>=1.0; extra == 'dev'
Requires-Dist: pandas>=2.0; extra == 'dev'
Requires-Dist: pykrx>=1.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.4; extra == 'dev'
Requires-Dist: setuptools<81,>=68; extra == 'dev'
Requires-Dist: yfinance>=0.2; extra == 'dev'
Provides-Extra: full
Requires-Dist: anthropic>=0.40; extra == 'full'
Requires-Dist: fastmcp>=2.0; extra == 'full'
Requires-Dist: finance-datareader>=0.9; extra == 'full'
Requires-Dist: httpx>=0.27; extra == 'full'
Requires-Dist: keyring>=25.0; extra == 'full'
Requires-Dist: numpy>=1.26; extra == 'full'
Requires-Dist: openai>=1.0; extra == 'full'
Requires-Dist: pandas>=2.0; extra == 'full'
Requires-Dist: pykrx>=1.0; extra == 'full'
Requires-Dist: setuptools<81,>=68; extra == 'full'
Requires-Dist: yfinance>=0.2; extra == 'full'
Provides-Extra: llm
Requires-Dist: anthropic>=0.40; extra == 'llm'
Requires-Dist: openai>=1.0; extra == 'llm'
Provides-Extra: market-data
Requires-Dist: finance-datareader>=0.9; extra == 'market-data'
Requires-Dist: httpx>=0.27; extra == 'market-data'
Requires-Dist: pykrx>=1.0; extra == 'market-data'
Requires-Dist: setuptools<81,>=68; extra == 'market-data'
Requires-Dist: yfinance>=0.2; extra == 'market-data'
Provides-Extra: mcp
Requires-Dist: fastmcp>=2.0; extra == 'mcp'
Provides-Extra: network
Requires-Dist: httpx>=0.27; extra == 'network'
Requires-Dist: keyring>=25.0; extra == 'network'
Provides-Extra: quant
Requires-Dist: numpy>=1.26; extra == 'quant'
Requires-Dist: pandas>=2.0; extra == 'quant'
Description-Content-Type: text/markdown

# RAWR

[![Python 3.12+](https://img.shields.io/badge/python-3.12%2B-3776AB.svg)](./pyproject.toml)
[![CI](https://github.com/snowjang24/rawr-tools/actions/workflows/ci.yml/badge.svg)](https://github.com/snowjang24/rawr-tools/actions/workflows/ci.yml)
[![MCP](https://img.shields.io/badge/MCP-enabled-0A7EA4.svg)](#mcp-surface)
[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](./LICENSE)

> 🇰🇷 한국어 사용자: [README.ko.md](./README.ko.md)

RAWR is an async-first Python toolkit for Korean stock trading workflows.
It is designed to work in three modes:

- as a terminal CLI for lookup, analysis, scoring, and guarded trade flows
- as an importable FastMCP server for agent and tool integrations
- as a local research and trading knowledge layer backed by SQLite

RAWR is strongest on Korean market workflows today. Selected US support exists for EDGAR-backed disclosure lookup and several framework-style analyses, but it is not full market parity yet.

## Table of Contents

- [Project Docs](#project-docs)
- [Open Source Distribution Model](#open-source-distribution-model)
- [Why RAWR](#why-rawr)
- [Who This Is For](#who-this-is-for)
- [Feature Summary](#feature-summary)
- [Requirements](#requirements)
- [Installation](#installation)
- [Dependency Extras](#dependency-extras)
- [Configuration](#configuration)
- [Quick Start](#quick-start)
- [Library Usage](#library-usage)
- [Stability, Deprecation, and Support Policy](#stability-deprecation-and-support-policy)
- [How To Use RAWR](#how-to-use-rawr)
- [Architecture](#architecture)
- [Examples](#examples)
- [Contributing](#contributing)
- [Security](#security)
- [Maintenance and Stretch Work](#maintenance-and-stretch-work)
- [CLI Overview](#cli-overview)
- [Agent-Friendly CLI](#agent-friendly-cli)
- [CLI Plugin Contract](#cli-plugin-contract)
- [MCP Surface](#mcp-surface)
- [Typical Workflows](#typical-workflows)
- [Market Support Matrix](#market-support-matrix)
- [Deployment](#deployment)
- [Project Layout](#project-layout)
- [Development](#development)
- [FAQ / Troubleshooting](#faq--troubleshooting)
- [License Status](#license-status)
- [Current Limitations](#current-limitations)
- [Safety Notes](#safety-notes)

## Project Docs

- [CHANGELOG](./CHANGELOG.md)
- [CONTRIBUTING](./CONTRIBUTING.md)
- [SECURITY](./SECURITY.md)
- [Docs Index](./docs/README.md)
- [AI and Agent Runtime](./docs/ai-agent-runtime.md)
- [Public Python API](./docs/api-reference.md)
- [CLI Reference](./docs/cli-reference.md)
- [MCP Reference](./docs/mcp-reference.md)
- [Skills Reference](./docs/skills.md)
- [Extension Template](./docs/extension-template.md)
- [Operations](./docs/operations.md)
- [Implementation Roadmap](./docs/implementation-roadmap.md)
- [OSS Library Tracker](./docs/oss-library-todo.md)
- [Release Guide](./docs/release-guide.md)
- [US Trading Quickstart (KR)](./docs/superpowers/guides/2026-04-25-us-trading-quickstart.md)
- [KIS Overseas Sandbox Validation](./docs/superpowers/guides/2026-04-25-kis-overseas-sandbox-validation.md)

## Open Source Distribution Model

RAWR is provided as a local-first open source runtime:

- `rawr-tools` is the Python package for CLI, library, local state, MCP, and
  bundled skills.
- `rawr-tools[mcp]` enables the FastMCP server surface for agents and tool
  clients.
- bundled skills are included in the Python wheel under `rawr/skills`.

## Why RAWR

RAWR is not just a thin broker wrapper. It combines:

- market access primitives around KIS
- KRX-specific market rules such as tick sizes, market hours, and trading costs
- quantitative utilities for indicators, risk, scoring, backtests, and portfolio analysis
- local knowledge storage for journals, research notes, watchlists, graph links, and strategy history
- agent-friendly surfaces through MCP tools, packaged bundled skills, and machine-readable CLI commands

## Who This Is For

RAWR is designed for operators who want one local runtime for:

- discretionary research in a terminal
- quant-style scoring and backtesting
- semi-automated trading with explicit approval points
- agent integrations through MCP or JSON-first CLI commands
- local-first persistence for journals, notes, strategies, sessions, and audit trails

RAWR is a good fit if you want:

- a Python-native toolkit instead of a hosted SaaS workflow
- KRX-aware order validation and market rules
- a split between human CLI control and agent/tool execution
- a semi-auto model where the system proposes and validates, but you still control approval

RAWR is not positioned as a fully autonomous trading bot. The shipped path is still safety-first and approval-gated.

## Feature Summary

### Market and trading

- Quote lookup and ticker search
- Account balance and holdings inspection
- Read-only portfolio books for cross-account KR/US cash and holdings snapshots
- Guarded order preview and validation
- Semi-auto trade plans with approval-gated execution
- KRX market-hour and price-rule awareness

### Quant and research

- Technical indicators such as RSI, MACD, and Bollinger Bands
- RAWR composite score and factor-model ranking
- Risk metrics such as VaR, Sharpe, Sortino, MDD, and beta
- Backtest, Monte Carlo simulation, and walk-forward tools
- Disclosure and news analysis
- Wall Street-style framework analysis modules

### Knowledge and automation

- Local trade journal and research note storage
- Watchlists and graph-based entity relationships
- Strategy outcome tracking and recommendations
- Alerts, schedules, trust levels, kill switch, and trade session state

### Agent and integration surface

- Importable `FastMCP` app exposed as `rawr.mcp.server:mcp`
- 116 MCP tools across market, quant, trading, automation, knowledge, framework, decision, portfolio, and signal modules
- Discoverable CLI tool contracts through `rawr tool ...`
- 17 packaged bundled workflow skills through `rawr skill ...`
- 4 built-in workflow-agent pack manifests through `rawr agent ...`
- Optional LLM-assisted signal aggregation and sentiment tools through `signal_tools`
- Local environment diagnostics through `rawr doctor`

## Requirements

- Python `3.12+`
- Base install for the core CLI, library, and local storage; optional extras unlock MCP, market-data, quant, and full runtime bundles
- KIS account and API credentials for most Korean market and trading flows
- macOS Keychain or environment variables for secret loading
- Optional: `DART_API_KEY` for Korean disclosure lookups
- Optional: `KRX_OPENAPI_KEY` or `[krx].api_key` for official KRX Data Marketplace OpenAPI lookups
- Optional: `RAWR_EDGAR_USER_AGENT` for SEC EDGAR access

## Installation

### Development install

```bash
git clone <your-repo-url>
cd rawr-tools
python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install -e ".[dev]"
```

### Install from a built wheel

```bash
python -m pip install build twine
python -m build
python -m twine check dist/*
python -m pip install dist/*.whl
```

## Dependency Extras

Start with the base install for the core CLI, library, and local storage.
Use the extras below when you need MCP, market-data, quant, or the full runtime bundle.
For source checkouts, use editable installs. For published installs, use the matching `rawr-tools[...]` extra.

```bash
git clone <your-repo-url>
cd rawr-tools
python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install -e .
```

### Install profile matrix

| Profile | Published install | Unlocks |
| --- | --- | --- |
| `base` | `python -m pip install rawr-tools` | Core CLI, local config/bootstrap, doctor, JSON tool registry, local SQLite state |
| `mcp` | `python -m pip install "rawr-tools[mcp]"` | MCP server entrypoint, MCP health/readiness, MCP transports |
| `market-data` | `python -m pip install "rawr-tools[market-data]"` | KRX market-data providers, official KRX OpenAPI fallback, lookup and market-data-backed CLI/MCP flows |
| `quant` | `python -m pip install "rawr-tools[quant]"` | Indicators, scoring, risk, backtest, portfolio analysis |
| `llm` | `python -m pip install "rawr-tools[llm]"` | Optional OpenAI/Anthropic dependencies for structured signal and sentiment tools |
| `full` | `python -m pip install "rawr-tools[full]"` | Complete local runtime: MCP + network + market-data + quant + LLM dependencies |

Recommended paths:

- If you only want bootstrap and local storage, use `base`
- If agents need MCP, use `mcp`
- If you only need LLM-backed signal tools, add `llm`
- If you want research and trading workflows to work end-to-end, use `full`

Add the extras below when you need optional runtime surfaces.

### `mcp`

```bash
python -m pip install -e ".[mcp]"
```

Adds the packaged MCP server entrypoint and the FastMCP runtime.
Published install: `python -m pip install "rawr-tools[mcp]"`

### `market-data`

```bash
python -m pip install -e ".[market-data]"
```

Adds the market data providers used for KRX data lookups and market-data-backed CLI and MCP paths, including the official KRX OpenAPI HTTP client.
Published install: `python -m pip install "rawr-tools[market-data]"`

### `quant`

```bash
python -m pip install -e ".[quant]"
```

Adds the quant stack used by indicators, scoring, risk, and portfolio analysis flows.
Published install: `python -m pip install "rawr-tools[quant]"`

### `llm`

```bash
python -m pip install -e ".[llm]"
```

Adds the optional OpenAI and Anthropic SDKs used by `aggregate_signals` and `analyze_sentiment`.
Published install: `python -m pip install "rawr-tools[llm]"`

### `full`

```bash
python -m pip install -e ".[full]"
```

Installs all runtime extras: `mcp`, `network`, `market-data`, `quant`, and `llm`.
Use this when you want the broadest supported local runtime and do not need to trim dependencies.
Published install: `python -m pip install "rawr-tools[full]"`

The `network` dependency bucket is part of the shipped metadata for live KIS and EDGAR access, and it is included in `full` even though the primary install shortcuts above focus on the user-facing runtime bundles.

## Configuration

Bootstrap the local home directory and default config:

```bash
rawr init
rawr init --json
```

This creates:

- `~/.rawr/config.toml`
- `~/.rawr/rawr.db`
- `~/.rawr/policy.json`
- `~/.rawr/sessions/`

For packaged-runtime KIS account access, edit `[kis]` in `~/.rawr/config.toml`:

```toml
[kis]
account_no = "12345678-01"
is_paper = true
app_key = "your-app-key"
app_secret = "your-app-secret"
```

Environment variables remain useful for CI, development shells, and non-KIS integrations:

```bash
export DART_API_KEY="your-dart-key"
export KRX_OPENAPI_KEY="your-krx-openapi-key"
export RAWR_EDGAR_USER_AGENT="RAWR/0.1.0 contact@example.com"
```

Feature-specific configuration:

- KIS trading and account flows use `[kis].app_key` and `[kis].app_secret` in `~/.rawr/config.toml` by default. Process environment variables remain useful for CI and one-off development overrides.
- Paper mode always uses the single `[kis].account_no`. Production can split real accounts with `[kis.accounts.<key>]` profiles and `default_account`; pass `--account <key>` to `rawr balance`, `rawr holdings`, `rawr plan create`, `rawr plan trade`, and `rawr plan execute`, or `account_key=<key>` to order-preview tools.
- disclosure and news lookup use `[dart].api_key` in `~/.rawr/config.toml`, or `DART_API_KEY` from `rawr.env` or the process environment.
- Official KRX daily market data uses `[krx].api_key` in `~/.rawr/config.toml`, or `KRX_OPENAPI_KEY`/`KRX_API_KEY` from `rawr.env` or the process environment. When configured, RAWR uses it for listed equity/ETF/ETN daily OHLCV/fundamentals, non-realtime price fallback, ticker/product search fallback, ETF/ETN dedicated lookup commands, and KOSPI/KOSDAQ/KRX 300 market overview. Stock basic-info services enrich listing metadata when approved; RAWR falls back to daily rows when those services are unavailable. KIS remains the preferred realtime quote source; when official KRX data is unavailable, RAWR falls back to existing provider paths where available.
- SEC EDGAR access uses `RAWR_EDGAR_USER_AGENT`
- LLM-backed signal and decision tools use `RAWR_LLM_PROVIDER`, `RAWR_LLM_MODEL`, and `RAWR_LLM_API_KEY`; optional settings include `RAWR_LLM_BASE_URL` for provider endpoint override, provider-neutral `RAWR_LLM_OUTPUT_LANGUAGE`, and OpenAI/OpenRouter `RAWR_LLM_REASONING_EFFORT`
- Investment-committee debate mode is advisory-only; `[committee]` can set multi-seat lenses, max rounds, chair/model overrides, and the optional Claude/Codex cross-verification agent.
- Telegram notifications use the `[notifications.telegram]` section in `~/.rawr/config.toml` with `bot_token` and `chat_id`

Recommended KIS credential loading order:

1. Keychain
2. `~/.rawr/config.toml`
3. process environment
4. legacy `rawr.env` files (`~/.rawr/rawr.env`, `/etc/rawr/rawr.env`)

`rawr.env` is kept as a compatibility fallback for older local setups and CI-style secret injection. New packaged-runtime installs should edit `~/.rawr/config.toml` after `rawr init`.

The env template remains available when that fallback is intentional:

```bash
rawr init
cp ~/.rawr/rawr.env.example ~/.rawr/rawr.env
```

Notes:

- `is_paper = true` should remain enabled unless you intentionally want live trading.
- Most quote, account, and trading flows depend on valid KIS credentials.
- `rawr init` now writes a commented `[fred]` section in `~/.rawr/config.toml`; set `[fred].api_key` for US Kelly sizing.
- `rawr init` writes a `[krx]` section for the official KRX Data Marketplace OpenAPI. KRX requires an authentication key and per-service API usage approval.
- Local SQLite state is machine-specific operational data.

## Quick Start

If you want the shortest path from install to first useful result, use this section.

### Verify base install

```bash
rawr --help
rawr init
rawr doctor
```

Expected result:

- `rawr --help` prints the top-level CLI groups
- `rawr init` creates the local runtime home under `~/.rawr`
- `rawr doctor` confirms config, DB, and credentials status

### Verify MCP install

Install the `mcp` extra first:

```bash
python -m pip install -e ".[mcp]"
```

Then verify the packaged MCP surface:

```bash
rawr mcp health --json
rawr mcp readiness --json
```

### Verify market-data and quant installs

Install the matching extras first:

```bash
python -m pip install -e ".[market-data]"
python -m pip install -e ".[quant]"
```

Then run the feature checks:

```bash
rawr price 005930
rawr search 삼성전자
rawr etf search KODEX
rawr etf price 069500
rawr tool call get_market_overview --arg market=krx300 --json
rawr indicators 005930
rawr rawr-score 005930
```

Use these to confirm three things quickly:

- quote and lookup flows work
- indicator and scoring modules can fetch or compute data
- your local environment is good enough for research before you touch any live path

### First agent checks

Bundled skills are packaged with supported installs:

```bash
rawr tool list --json
rawr tool schema get_rawr_score --json
rawr tool validate-args get_price --arg code=005930 --json
rawr skill list --json
rawr skill show auto-research --json
```

If `rawr skill list --json` is empty in a packaged install, treat that as a
broken or outdated release and verify the installed package includes bundled
skill assets.

### Start the MCP server

```bash
rawr mcp serve
```

Use `stdio` or the default local mode when integrating with CLI agents on the same machine. Use HTTP only when you intentionally want a network-facing MCP process.

## Library Usage

RAWR also exposes a supported Python-facing facade for library consumers.

Use the facade for supported imports. Treat `rawr.api` as the supported general-purpose import surface. Treat deep internal module paths as implementation details unless they are explicitly documented.

One documented exception exists for MCP server wiring: `rawr.mcp.server:mcp` is the supported entrypoint when you need to expose RAWR as an MCP server. Use `rawr.api` for library code and `rawr.mcp.server:mcp` for MCP integration setup.

```python
from pathlib import Path

from rawr.api import RawrDB
from rawr.api import TradePlanRepository

db = RawrDB(Path("~/.rawr/rawr.db").expanduser())
db.initialize()
plans = TradePlanRepository(db)

print(plans.get("missing-plan"))
```

Base-install-safe domain models and order validation helpers are also exposed:

```python
from rawr.api import Order
from rawr.api import OrderValidator
from rawr.api import SafetyConfig

order = Order(code="005930", side="buy", qty=2, price=50003)
validator = OrderValidator(SafetyConfig(max_order_value=1_000_000))
print(validator.validate(order, prev_close=50_000))
```

`TradePlanService` is also exposed through `rawr.api`, but its default provider
wiring can require optional market-data dependencies. Install the relevant
extras or pass explicit test providers before using it in lightweight library
contexts.

Prefer the facade for application code and integrations so your imports stay stable as the internal module layout evolves.

## Stability, Deprecation, and Support Policy

- Public Python API: `rawr.api` is the supported general-purpose import surface. Top-level `rawr` exports that delegate to `rawr.api` are also supported. Deep imports under `rawr.core`, `rawr.cli`, `rawr.mcp`, and other package internals are implementation details unless this README or the reference docs explicitly document them.
- MCP entrypoint: `rawr.mcp.server:mcp` is the supported MCP server wiring entrypoint. MCP tool names, schemas, and market-support metadata exposed through `rawr tool schema ...` are the compatibility surface; internal MCP module layout is not.
- Plugins: `rawr.cli_plugins`, `rawr.mcp_plugins`, and `rawr.skill_plugins` are Phase 1 extension contracts for trusted local packages. Collisions fail closed, partial failures are reported through inspect commands, and plugin authors should pin and test against compatible RAWR versions.
- CLI: documented command names and JSON output contracts are intended to remain stable. Human-readable text output may change for clarity. Commands described as placeholders or unsupported should not be treated as stable automation targets.
- Internal modules: modules not documented as public may move, change signatures, or gain optional dependency boundaries without deprecation.
- Python and platforms: RAWR requires Python `3.12+`. Package metadata is OS-independent, but some credential flows depend on macOS Keychain or environment variables.
- Market support: Korean market workflows are the primary supported path. US support is selective and should be checked per tool or skill via schema/metadata. Unsupported markets fail closed instead of silently falling back.
- Deprecations: public API, documented CLI JSON contracts, MCP entrypoint behavior, and plugin contracts should receive changelog or README notice before removal when practical. Security fixes, broker/provider breakage, and undocumented internals may change without a full deprecation window.

## How To Use RAWR

The most useful mental model is:

- `rawr price/search/indicators/rawr-score/factor-*` for fast human research
- `rawr tool ...` for machine-readable tool discovery and execution
- `rawr plan ...` for semi-auto trade planning and approval
- `rawr session/audit/observe/policy` for runtime control and governance
- `rawr mcp serve` when another tool should call RAWR through MCP

You usually interact with RAWR in one of four patterns.

### 1. Manual Research In The Terminal

This is the fastest way to inspect one ticker.

```bash
rawr search 삼성전자
rawr price 005930
rawr indicators 005930
rawr rawr-score 005930
rawr factor-score 005930
```

Use this when you want a quick answer, not a long-running workflow.

### 2. Semi-Auto Trade Planning

This is the shipped approval-gated trading workflow.

```bash
rawr plan create 005930 --strategy mean_reversion --json
rawr plan create 005930 --strategy mean_reversion --decision-run-id <decision-run-id> --json
rawr plan create 005930 --strategy mean_reversion --account isa --json
rawr plan show <plan-id> --json
rawr plan review <plan-id> --json
rawr plan approve <plan-id> --owner cli --json
rawr plan review <plan-id> --live-price 71000 --qty 1 --side buy --json
rawr plan trade <plan-id> --qty 1 --price 71000 --side buy --account isa --policy-ack --json
rawr tool call place_order \
  --arg code=005930 \
  --arg side=buy \
  --arg qty=1 \
  --arg price=71000 \
  --arg confirm=false \
  --arg plan_id=<plan-id> \
  --policy-ack \
  --json
```

For KIS US trading readiness, run the read-only smoke before the first order:

```bash
rawr doctor --json
rawr tool call check_us_trading_readiness --arg code=AAPL --json
```

What happens in this flow:

1. `plan create` computes a trade plan from market data, backtest output, walk-forward output, plan metrics, and the evidence gate. Add `--decision-run-id` to attach saved structured decision evidence.
2. `plan show` lets you inspect the stored plan, including probability, EV-after-cost, confidence, `strategy_stage`, `evidence_score`, `evidence_failures`, `evidence_summary`, and invalidation reason.
3. `plan review` summarizes approval readiness, blockers, warnings, next actions, and the review-only safety envelope.
4. `plan approve` grants a bounded approval lease.
5. `plan review --live-price ... --qty ...` performs a final execution-envelope check before any live submission.
6. `tool call place_order ... confirm=false ... plan_id=<plan-id>` performs a guarded live execution path that revalidates:
   - plan approval state
   - plan expiry and approval expiry
   - symbol match
   - allowed quantity
   - price bounds for entries
   - buy-side live readiness: `strategy_stage` must be `limited_live`
   - exit-side rules for sells

This is the recommended model for real use today.

### 3. Agent-Oriented JSON Execution

If you want Codex CLI, Claude CLI, or another orchestrator to work against RAWR without MCP first, use the JSON-first CLI surfaces:

```bash
rawr tool list --json
rawr tool schema get_price --json
rawr tool call get_price --arg code=005930 --json
rawr skill list --json
rawr skill run auto-research 005930 --json
```

This is useful when:

- you want explicit process-level commands
- you need structured JSON in shell pipelines
- you want to inspect tool or skill contracts before wiring an MCP client

### 4. MCP-Based Integration

If another agent runtime already speaks MCP, run RAWR as an MCP server:

```bash
rawr mcp serve --transport stdio
```

Then expose it to the external client as an MCP tool source.

Use MCP when:

- you want tool discovery and invocation through an MCP client
- you want to keep RAWR as the market/trading backend and another tool as the orchestration layer
- you need a cleaner integration surface than shell commands

## Architecture

RAWR is designed as a local-first trading runtime with separate surfaces for humans, agents, and execution safety.

```text
                        +---------------------------+
                        |      Codex / Claude       |
                        |   shell CLI or MCP user   |
                        +-------------+-------------+
                                      |
                     +----------------+----------------+
                     |                                 |
                     v                                 v
            +------------------+              +------------------+
            |   Human CLI      |              |   MCP Surface    |
            | rawr ...         |              | rawr mcp serve   |
            +--------+---------+              +---------+--------+
                     |                                  |
                     +----------------+-----------------+
                                      |
                                      v
                           +----------------------+
                           |   Core Domain Layer  |
                           |----------------------|
                           | plans                |
                           | market               |
                           | quant/backtest       |
                           | knowledge            |
                           | automation           |
                           | policy/session/audit |
                           +----------+-----------+
                                      |
                +---------------------+----------------------+
                |                                            |
                v                                            v
      +-------------------------+                 +----------------------+
      | Local State             |                 | External Providers   |
      |-------------------------|                 |----------------------|
      | ~/.rawr/config.toml     |                 | KIS API              |
      | ~/.rawr/rawr.db         |                 | pykrx / FDR / yf     |
      | ~/.rawr/policy.json     |                 | DART / EDGAR         |
      | ~/.rawr/sessions/       |                 | optional news/macros |
      +-------------------------+                 +----------------------+
```

### Semi-Auto Trading Architecture

The semi-auto trading path is intentionally split into six stages:

1. `plan create`
   Market data, backtest output, walk-forward output, probability metrics, and evidence checks become a stored trade plan.
2. `plan review`
   The operator checks whether the plan is approval-ready and whether evidence, expiry, status, or live-readiness blockers remain.
3. `plan approve`
   A human grants an approval lease in the CLI.
4. `plan review --live-price ... --qty ...`
   RAWR checks the current price and intended quantity against the approved envelope without submitting an order.
5. `tool call place_order ... confirm=false --arg plan_id=... --policy-ack`
   RAWR revalidates the approved envelope before broker submission. Buy-side live execution requires `strategy_stage=limited_live`; sell-side execution remains available for risk reduction when the plan is otherwise valid.
6. execution state transition
   The plan moves through approval and execution states so it cannot be replayed accidentally.

This is the core boundary:

- agents can propose
- the operator approves
- RAWR enforces the execution envelope

Evidence stages are `research_only`, `backtest_qualified`, `walk_forward_qualified`, `paper_ready`, and `limited_live`. The stored `evidence_score`, `evidence_failures`, and `evidence_summary` explain live readiness and failure reasons, and `rawr plan show <plan-id> --json` returns those fields through the normal plan payload.

## Examples

These are representative JSON payloads for the main shipped workflows. The exact numbers will vary, but the shape is what downstream tooling should expect.

The concrete extension example package lives at `examples/rawr_extension_demo`.
It shows the three plugin surfaces together and can be verified with
`rawr demo-ops status` after installing `examples/rawr_extension_demo`.

### Example: `rawr plan create ... --json`

```json
{
  "ok": true,
  "data": {
    "plan_id": "plan_4f1d2a8c3b",
    "code": "005930",
    "market": "kr",
    "strategy_name": "mean_reversion",
    "thesis": "mean reversion setup derived from RAWR backtest and walk-forward analysis",
    "entry_price_min": 70645.0,
    "entry_price_max": 71355.0,
    "stop_loss_price": 69225.0,
    "take_profit_price": 73130.0,
    "position_size": 1,
    "risk_amount": 1420.0,
    "estimated_fees": 305.3,
    "raw_win_rate": 0.58,
    "recent_win_rate": 0.6,
    "walk_forward_win_rate": 0.55,
    "regime_adjustment": 0.01,
    "adjusted_win_probability": 0.6085,
    "expected_value_after_cost": 0.0085,
    "profit_loss_ratio": 1.8,
    "max_expected_loss": 1420.0,
    "confidence_score": 0.72,
    "strategy_stage": "limited_live",
    "evidence_score": 0.71,
    "evidence_failures": [],
    "evidence_summary": {
      "sample_size": 64,
      "walk_forward_win_rate": 0.55,
      "expected_value_after_cost": 0.0085,
      "max_drawdown": -0.14,
      "cost_sensitivity_passed": true
    },
    "approval_status": "pending",
    "created_at": "2026-04-15T05:00:00Z",
    "expires_at": "2026-04-15T05:30:00Z",
    "invalidation_reason": ""
  }
}
```

What matters most:

- `approval_status`
- `adjusted_win_probability`
- `expected_value_after_cost`
- `confidence_score`
- `strategy_stage`
- `evidence_score`
- `evidence_failures`
- `entry_price_min` / `entry_price_max`
- `invalidation_reason`

### Example: `rawr plan approve ... --json`

```json
{
  "ok": true,
  "data": {
    "plan_id": "plan_4f1d2a8c3b",
    "approval_status": "approved",
    "approved_by": "cli",
    "approved_at": "2026-04-15T05:04:00Z",
    "approval_expires_at": "2026-04-15T05:30:00Z"
  }
}
```

This is the point where the plan becomes executable, but only inside the approved envelope.

### Example: guarded live execution with `rawr tool call place_order ... --json`

```json
{
  "ok": true,
  "data": {
    "executed": true,
    "order_id": "0001234567",
    "plan_id": "plan_4f1d2a8c3b",
    "message": "주문 완료",
    "order": {
      "code": "005930",
      "side": "buy",
      "qty": 1,
      "price": 71000,
      "order_type": "limit",
      "total_value": 71000,
      "price_adjusted": false,
      "warnings": []
    }
  }
}
```

### Example: blocked execution

```json
{
  "ok": false,
  "error": {
    "type": "PlanExecutionBlocked",
    "message": "approval_expired",
    "context": {
      "allowed": false,
      "reason": "approval_expired",
      "plan_id": "plan_4f1d2a8c3b",
      "approval_expires_at": "2026-04-15T05:30:00Z"
    }
  }
}
```

Typical reasons you will see:

- `plan_not_found`
- `plan_not_approved`
- `plan_expired`
- `approval_expired`
- `code_mismatch`
- `qty_exceeds_plan`
- `price_outside_entry_range`

## Contributing

Contributions are welcome, but this repository is still operator-oriented and safety-sensitive, so changes should stay conservative.

Before opening a PR or patch:

1. open an issue or short proposal for behavior changes that affect trading, execution gating, or policy
2. keep scope narrow and avoid unrelated refactors
3. include or update tests for every behavior change
4. prefer fail-closed behavior over convenience on execution paths

Suggested local workflow:

```bash
git clone <your-repo-url>
cd rawr-tools
python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install -e ".[dev]"
ruff check .
pytest -q
```

Contribution guidelines:

- keep CLI output concise for humans and stable for JSON consumers
- preserve KRX-specific safety behavior unless there is a strong reason to change it
- add regression tests when changing plan lifecycle or order execution behavior
- update `README.md`, `docs/cli-reference.md`, or `docs/mcp-reference.md` when user-facing contracts change

Good first contribution areas:

- documentation improvements
- additional CLI examples
- test coverage expansions
- non-breaking UX polish for JSON/text output

## Security

RAWR interacts with market credentials and can participate in real order submission, so responsible disclosure matters.

If you discover a security issue:

- do not post secrets, exploit details, or live-account material in public issues
- report the issue privately to the maintainer first
- include reproduction steps, impact, and any suggested mitigation

Security-sensitive areas in this repo:

- credential loading and secret handling
- live order execution paths
- plan approval and execution gating
- session tokens and reattach flows
- policy and hook execution surfaces

Operational security guidance:

- keep `is_paper = true` unless you explicitly intend to trade live
- do not run live credentials on shared machines
- treat `~/.rawr/` as sensitive operator state
- rotate credentials if they were ever exposed in logs, screenshots, or shell history

## Maintenance and Stretch Work

The current direction is to deepen RAWR as a safety-first AI-assisted quant terminal rather than turn it into a blind autonomous trader.

Current maintenance:

- strengthen the trade-plan lifecycle beyond the current create/show/approve flow
- keep CLI, MCP, Python, and extension examples aligned with executable coverage
- improve US-market parity where contracts are already partially exposed
- keep docs, help text, and runtime behavior aligned

Stretch work:

- richer plan execution and exit orchestration
- stronger policy templates for paper/live trading modes
- improved observability around automation and execution outcomes
- deeper strategy-history feedback into plan generation

Reference documents:

- [docs/implementation-roadmap.md](./docs/implementation-roadmap.md)
- [docs/ai-agent-runtime.md](./docs/ai-agent-runtime.md)
- [docs/operations.md](./docs/operations.md)
- [docs/cli-reference.md](./docs/cli-reference.md)
- [docs/mcp-reference.md](./docs/mcp-reference.md)

## CLI Overview

Top-level commands currently exposed by `rawr`:

| Command | Purpose |
| --- | --- |
| `price` | Get current price for a stock |
| `search` | Search stocks by name or code |
| `indicators` | Print RSI, MACD, and Bollinger Bands |
| `rawr-score` | Print RAWR score breakdown |
| `analysis` | Run structured research and analysis workflows |
| `order` | Preview a guarded buy or sell order |
| `plan` | Create, inspect, review, approve, and submit approved trade plans |
| `balance` | Print account cash balance |
| `holdings` | Print current holdings |
| `portfolio` | Inspect read-only cross-account portfolio books |
| `trades` | Sync and inspect locally stored broker trade records |
| `graph-link` | Create or update a graph relationship |
| `graph-neighbors` | Inspect graph neighbors |
| `factor-score` | Show VMQ factor score for one stock |
| `factor-rank` | Rank multiple candidate stocks |
| `tool` | Inspect MCP tool contracts |
| `skill` | Inspect and run bundled workflow skills |
| `init` | Bootstrap a local RAWR config, DB, and runtime home |
| `session` | Inspect, prune, replay, resume, and cancel stored execution artifacts |
| `audit` | Inspect and export structured runtime audit events |
| `observe` | Summarize, tail, and export runtime observability data |
| `policy` | Show or set the active execution governance mode |
| `hook` | Register and manage runtime hooks around tool and skill execution |
| `plugin` | Inspect discovered CLI, MCP, and skill plugin packages |
| `doctor` | Check local environment and agent surface readiness |
| `mcp` | Run or manage the packaged MCP server |
| `codex` | Install RAWR Codex MCP config and native skills |

## Recommended Usage Paths

The CLI is broad, but most users should start with one of these paths.

### Research Only

```bash
rawr search 삼성전자
rawr price 005930
rawr indicators 005930
rawr rawr-score 005930
rawr analysis daily-brief 005930 000660 --market kr --json
rawr analysis daily-brief 005930 000660 --market kr --preflight --portfolio-risk --json
rawr analysis decision 005930 --market kr --json
rawr analysis decision 005930 --market kr --committee --json
```

### Research Plus Agent Tooling

```bash
rawr codex install
rawr tool list --json
rawr tool schema get_rawr_score --json
rawr skill run auto-research 005930 --json
rawr analysis daily-brief 005930 000660 035420 --market kr --strategy mean_reversion --json
rawr analysis decision 005930 --market kr --json
rawr analysis decision 005930 --market kr --committee --cross-verify --json
rawr analysis decision-verify <run_id> --json
rawr skill run quant-research "mean reversion works after costs" --arg code=005930 --arg strategy=mean_reversion --json
rawr skill run market-regime --arg index_code=005930 --arg market=kr --arg timeframe=short-term --json
```

`rawr codex install` writes the RAWR MCP server entry to `~/.codex/config.toml`,
installs Codex-native RAWR skills under `~/.agents/skills`, and keeps legacy
prompt files under `~/.codex/prompts` for older Codex builds. Current Codex
uses skill invocations such as `$rawr-status`, `$rawr-portfolio`,
`$rawr-research`, and `$rawr-order-preview`; restart Codex after installing so
native skill discovery refreshes.

### Monitor Strategy Validation

The dashboard monitor can store a preview-only strategy candidate, validate it
against the 19-check research gate, and require the saved validation state before
emitting monitor candidates.

```bash
rawr dashboard monitor strategy preset swing-cci-regime --init-report --json
rawr dashboard monitor strategy catalog --json
rawr dashboard monitor strategy status swing-cci-regime-v1
rawr dashboard monitor run-once --require-strategy-validation --strategy-id swing-cci-regime-v1
```

The built-in `swing-cci-regime` preset captures the CCI(20), CNN Fear & Greed,
S&P 500 breadth, Nasdaq MA regime, and -5% invalidation rules discussed for the
preview monitor strategy. It does not submit live orders.

HTTP clients can bootstrap the same strategy through
`POST /api/monitor/strategies/preset` with `init_report=true`.

### Semi-Auto Trading

```bash
rawr policy template apply live-trade-guardrails --json
rawr plan create 005930 --strategy mean_reversion --json
rawr plan review <plan-id> --json
rawr plan approve <plan-id> --owner cli --json
rawr plan review <plan-id> --live-price 71000 --qty 1 --side buy --json
rawr tool call place_order --arg code=005930 --arg side=buy --arg qty=1 --arg price=71000 --arg confirm=false --arg plan_id=<plan-id> --policy-ack --json
```

US plan execution note:

- `rawr tool call place_order --arg market=us ...` is supported by current CLI market metadata.
- US KIS order tools accept `--arg exchange_code=NASD|NYSE|AMEX`; the default is `NASD`.
- Live submission still requires `confirm=false`, an approved `plan_id`, and policy allowance (`--policy-ack` when required).
- `rawr plan trade <plan-id> ...` remains the higher-level CLI path for plan-driven execution; add `--account <key>` to route through a configured production account.
- US order safety checks convert USD notional values to KRW for max-order guardrails; missing FX data fails closed.
- MCP clients that call order tools through `rawr.mcp.server:mcp` use the same policy/session/hooks envelope as `rawr tool call`.

### Runtime Operations

```bash
rawr doctor --json
rawr observe summary --json
rawr audit list --json
rawr policy show --json
rawr session list --json
rawr trades sync --date 2026-05-14 --json
rawr trades summary --date 2026-05-14 --json
```

Use `rawr doctor --json` first to confirm bootstrap and credential health, then `rawr observe summary --json` to see whether the runtime is healthy or needs action. If the summary reports a policy-related problem, follow up with `rawr policy explain --kind tool --name place_order --required-mode live-trade --json` and inspect recent denials with `rawr audit list --event-type policy_decision --json`.

## CLI Reference

### `rawr price CODE`

Returns current quote information for a ticker.

Example:

```bash
rawr price 005930
```

Output includes code, name, price, change, volume, and timestamp.

### `rawr search QUERY`

Searches stocks by name or code prefix.

Example:

```bash
rawr search 삼성
```

### `rawr indicators CODE`

Prints RSI, MACD, MACD signal/histogram, and Bollinger Band levels.

Example:

```bash
rawr indicators 005930
```

### `rawr rawr-score CODE`

Prints the RAWR composite score and its component breakdown.

### Semi-auto trade plan workflow

Use the plan lifecycle when you want backtest-first sizing and a bounded approval before any live order:

```bash
rawr plan create 005930 --strategy mean_reversion --json
rawr plan show <plan-id> --json
rawr plan review <plan-id> --json
rawr plan approve <plan-id> --owner cli --json
rawr plan review <plan-id> --live-price 71000 --qty 1 --side buy --json
rawr tool call place_order \
  --arg code=005930 \
  --arg side=buy \
  --arg qty=1 \
  --arg price=71000 \
  --arg confirm=false \
  --arg plan_id=<plan-id> \
  --policy-ack \
  --json
```

- `rawr plan create` stores a trade plan with adjusted probability, EV-after-cost, and a bounded entry range.
- `rawr plan review` is a review-only checkpoint for approval readiness, execution readiness, blockers, warnings, and next actions; it never submits an order.
- `rawr plan approve` grants a CLI approval lease tied to the plan expiry window.
- After approval, the shipped live paths are `rawr plan trade ...`, `rawr plan execute ...`, and the lower-level `rawr tool call place_order ... --arg confirm=false --arg plan_id=<plan-id> --policy-ack --json`; each path revalidates the approved envelope before broker submission.

What to check before approving a plan:

- `adjusted_win_probability`
- `expected_value_after_cost`
- `confidence_score`
- `entry_price_min` and `entry_price_max`
- `position_size`
- `invalidation_reason`

What blocks live execution even after approval:

- expired approval lease
- expired plan window
- symbol mismatch
- quantity above approved plan size
- entry price outside approved range
- reused or already consumed plan

Example:

```bash
rawr rawr-score 005930
```

Useful when you need a compact summary instead of running a full research pipeline.

### `rawr order SIDE CODE QTY PRICE`

Previews a buy or sell order with validation.

Examples:

```bash
rawr order buy 005930 1 70000
rawr order sell 005930 2 76000
```

Characteristics:

- validates the order against local safety rules
- attempts to fetch a recent market price when available
- prints an explicit preview-only warning in command output
- does not place the order through the CLI
- is intentionally preview-oriented; execute through `rawr plan trade` or `rawr tool call place_order ... --arg confirm=false ...`

### `rawr balance`

Prints settled, unsettled, and available cash balances.

```bash
rawr balance
```

### `rawr holdings`

Prints current holdings with quantity, average price, current price, and P&L.

```bash
rawr holdings
```

### `rawr portfolio books`

Lists configured read-only portfolio books.

```bash
rawr portfolio books
rawr portfolio books --json
```

### `rawr portfolio snapshot`

Builds a read-only normalized snapshot for a configured book or all enabled
accounts. Existing trade and plan commands remain account-specific; portfolio
commands do not submit orders.

```bash
rawr portfolio snapshot --book total
rawr portfolio snapshot --book total --json
rawr portfolio snapshot --all-accounts --base KRW --json
```

### `rawr trades`

Syncs and inspects the local broker execution ledger. `sync` fetches domestic
or US KIS filled executions for one trading day, stores fills, rebuilds the
daily summary, and records a memory event for future portfolio context.

```bash
rawr trades sync --date 2026-05-14 --json
rawr trades list --date-range 2026-05-14 --json
rawr trades summary --date 2026-05-14 --json
```

Pass `--market us` to use the KIS overseas `inquire-ccnl` fill endpoint.

### `rawr graph-link SOURCE_KEY TARGET_KEY RELATION_TYPE`

Creates or updates a graph relationship in the local knowledge store.

Examples:

```bash
rawr graph-link 005930 semiconductor belongs_to --target-type sector
rawr graph-link 005930 earnings_q1 linked_to --target-type event
```

### `rawr graph-neighbors ENTITY_KEY`

Lists neighboring graph entities for a stock or other entity type.

Examples:

```bash
rawr graph-neighbors 005930
rawr graph-neighbors 005930 --relation-type belongs_to --direction both --limit 20
```

### `rawr factor-score CODE`

Shows the Phase 3 VMQ factor score for a single stock.

```bash
rawr factor-score 005930
```

### `rawr factor-rank CODE [CODE ...]`

Ranks a candidate set using the same factor model.

```bash
rawr factor-rank 005930 000660 035420 --limit 10
```

### `rawr analysis decision CODE`

Runs a structured, research-only decision workflow and records a decision run when local RAWR storage is configured.

```bash
rawr analysis daily-brief 005930 000660 035420 --market kr --strategy mean_reversion --json
rawr analysis daily-brief 005930 000660 --market kr --refresh-outcomes --json
rawr analysis daily-brief 005930 000660 --market kr --preflight --json
rawr analysis daily-brief 005930 000660 --market kr --portfolio-risk --max-position-pct 0.20 --json
rawr analysis decision 005930 --market kr --json
rawr analysis decision AAPL --market us --no-save-decision --json
rawr analysis decision 005930 --analysis-date 2026-05-01 --perspective technical --perspective risk --json
rawr analysis decision 005930 --committee --cross-verify --json
rawr analysis decision 005930 --checkpoint --json
rawr analysis decision --resume sess_abc123 --json
rawr analysis decision-verify <run_id> --json
rawr analysis decision-refresh-outcomes --json
```

`rawr analysis daily-brief` runs the same research-only decision workflow across a short candidate list and returns plan-creation commands for buy candidates. Add `--refresh-outcomes` to update saved decision outcomes before producing the new brief, `--preflight` to include doctor/observability/policy readiness for the operator, and `--portfolio-risk` to include settled cash, current exposure, concentration warnings, and candidate risk budgets before plan creation. Sell decisions are surfaced as review actions for existing positions. It does not create plans, approve plans, or submit orders. The decision command creates research evidence and order-preview inputs only. `--committee` switches synthesis to advisory-only multi-seat debate mode, `--cross-verify` runs the optional Claude/Codex audit, and `decision-verify` can audit a saved committee run by ID. `--checkpoint` stores private local step artifacts and `--resume` reruns from the last completed step. If a checkpointed CLI run fails, use the printed `Resume with: ...` command or JSON `error.context.resume_session_id`. Outcome refresh records observed local journal/strategy outcomes for completed saved decisions when available. Live orders still require the normal approved plan, policy acknowledgement, market checks, and order validation path.

## Agent-Friendly CLI

RAWR exposes a second CLI layer aimed at agent and automation workflows.
The design goal is simple:

- discover capabilities without reading source first
- execute repeatable workflows with stable names
- expose machine-readable JSON when the caller is not a human

### Tool inspection

`rawr tool` is a local contract browser for MCP tools.

```bash
rawr tool list
rawr tool list --json
rawr tool schema get_rawr_score
rawr tool schema get_rawr_score --json
rawr tool schema get_trade_by_client_order_id --json
rawr tool call get_price --arg code=005930 --output text
rawr tool call get_price --arg code=005930 --json
rawr tool call search_journal --arg code=005930 --arg date_range=2026-04-01..2026-04-30 --json
rawr tool smoke get_price --json
```

Characteristics:

- reads tool signatures from source
- shows module, summary, and parameter defaults
- supports direct tool execution from the CLI
- supports `--arg KEY=VALUE`, `--args-file <json>`, and `--output json|text`
- useful for prompt assembly, wrappers, and agent planning

### Skill inspection and execution

`rawr skill` exposes bundled workflow prompts under `skills/`.

```bash
rawr skill list
rawr skill list --json
rawr skill show auto-research
rawr skill show wallstreet --json
rawr skill validate --json
```

Executable skills today:

- `auto-research`
- `auto-research-batch`
- `sector-analysis`
- `quant-research`
- `market-regime`
- `goldman`
- `dcf`
- `bridgewater`
- `jpmorgan`
- `blackrock`
- `citadel`
- `harvard`
- `bain`
- `renaissance`
- `mckinsey`
- `wallstreet`

Docs-only skill:

- `financial-report`

Examples:

```bash
rawr skill run auto-research 005930 --arg market=kr --json
rawr skill run auto-research 005930 --arg market=kr --arg save_report=false --json
rawr skill run auto-research-batch 005930 000660 035420 --json
rawr skill run sector-analysis semiconductor 005930 000660 035420 --json
rawr skill run goldman AAPL --arg market=us --json
rawr skill run blackrock moderate --json
rawr skill run bridgewater 005930 000660 035420 --json
rawr skill run wallstreet 005930 --arg framework=goldman,citadel --json
rawr skill run wallstreet 005930 --arg all=true --json
rawr skill run wallstreet moderate --arg framework=blackrock --json
rawr session list --json
rawr session show <session-id> --json
rawr session replay <session-id> --json
rawr session resume <session-id> --json
rawr session attach <session-id> --json
rawr session attach-info <session-id> --json
rawr session ps <session-id> --json
rawr session heartbeat <session-id> --json
rawr session detach <session-id> --json
rawr session logs <session-id> --json
rawr session cancel <session-id> --json
rawr session prune --keep 100 --older-than-days 30 --dry-run --json
rawr policy show --json
rawr policy set read-only --json
rawr audit list --json
rawr hook list --json
rawr hook register post_tool --command 'echo hook-ran' --json
```

Argument model:

- positional values are treated as the main target such as `code`
- extra named inputs use repeated `--arg KEY=VALUE`
- comma-separated values are parsed as lists
- boolean values accept `true` and `false`

Validation:

- `rawr skill validate` checks frontmatter completeness and runtime expectations
- bundled skills currently include 16 executable workflows plus the docs-only `financial-report` contract
- `docs_only` remains part of the metadata contract for catalog entries and plugins

### Agent pack inspection

`rawr agent` exposes built-in workflow-agent manifests inspired by Anthropic
financial-services style agent packaging. Agent packs describe role, tool
allowlists, RAWR CLI skills, Codex-native skills, connector assumptions, review
checkpoints, forbidden next actions, and output schemas. They are contracts for
orchestration and review; they do not run subagents or submit orders by
themselves. `rawr agent validate --json` checks tool references against
`rawr tool`, `rawr_skills` references against `rawr skill`, and
`codex_skills` references against packaged Codex asset skills.

```bash
rawr agent list --json
rawr agent show research-analyst --json
rawr agent show order-preview-controller --json
rawr agent validate --json
```

Built-in agent packs:

- `research-analyst`
- `portfolio-reviewer`
- `order-preview-controller`
- `ops-auditor`

### Session runtime

RAWR persists replayable artifacts for `tool call` and `skill run` executions when
the local session store is writable.

```bash
rawr session list --json
rawr session show <session-id> --json
rawr session replay <session-id> --json
rawr session resume <session-id> --json
rawr session attach <session-id> --json
rawr session attach-info <session-id> --json
rawr session ps <session-id> --json
rawr session heartbeat <session-id> --json
rawr session detach <session-id> --json
rawr session logs <session-id> --json
rawr session cancel <session-id> --json
rawr session prune --keep 100 --older-than-days 30 --dry-run --json
```

First-pass semantics:

- `tool call` and `skill run` return `session_id` when persistence succeeds
- session artifacts record lifecycle transitions such as `running -> completed`
- `replay` re-invokes the stored tool or skill using normalized params
- `resume` reattaches to `waiting`/`running` sessions when a live lease is possible
- `attach`, `heartbeat`, and `detach` manage the lease for a long-running session
- `--detach` on `tool call` and `skill run` launches a real background process tied to the session artifact
- `attach-info` returns the reattach contract, `ps` reports detached-process state, and `logs` reads recent detached-process output
- `cancel` marks the stored artifact as cancelled
- `prune` removes old terminal session artifacts, including the JSON session file, detached log, and transcript, while retaining the newest sessions

### Detached runtime recovery

Use `attach-info` first when a run is detached so you can decide whether to inspect state, reattach, or clean up stale artifacts.

```bash
rawr session attach-info <session-id> --json
rawr session ps <session-id> --json
rawr session logs <session-id> --json
rawr session prune --keep 100 --older-than-days 30 --dry-run --json
```

These JSON session runtime responses include `contract_version=1`, which lets remote clients validate the surface before parsing it.

### Policy and hooks

RAWR ships with a small governance layer for agent-facing execution.

```bash
rawr policy show --json
rawr policy set research --json
rawr policy rule list --json
rawr policy rule add --scope tool --effect require-confirm --pattern place_order --priority 200 --json
rawr policy rule add --scope skill --effect deny --pattern auto-* --when market=us --json
rawr policy explain --kind skill --name auto-research --required-mode research --metadata market=us --json
rawr hook list --json
rawr hook register pre_tool --command 'echo pre' --timeout-seconds 5 --fail-closed --json
rawr hook log --json
rawr hook audit --session-id <session-id> --json
rawr audit export --output runtime-events.json --format json --json
rawr hook disable <hook-id> --json
rawr hook unregister <hook-id> --json
```

Supported policy modes:

- `read-only`
- `research`
- `paper-trade`
- `live-trade`

Supported hook points:

- `pre_tool`
- `post_tool`
- `pre_skill`
- `post_skill`
- `pre_order`

Runtime behavior:

- policy decisions can block risky tool or skill execution before invocation
- explicit policy rules can `allow`, `deny`, or `require-confirm` on tool, skill, or module patterns
- rule conditions now support a first DSL across metadata fields via `eq`, `in`, `glob`, and `exists` matching
- higher-priority and more-specific rules are resolved deterministically before mode-only fallback
- order tools (`place_order`, `modify_order`, `cancel_order`) called through `rawr tool call` or the FastMCP server share the same policy/session/hooks envelope
- confirmation-gated order tools require `--policy-ack` on the CLI, or `policy_ack` / `_meta.rawr.policy_ack` from MCP clients
- session replay and resume preserve the original `policy_ack` value recorded with the session artifact
- hook failures are isolated from the core tool or skill result
- fail-closed hooks can intentionally block execution before the core action runs
- policy decisions and hook outcomes are written to the local runtime event log and a structured SQLite audit store
- `rawr audit list/export` exposes the broader runtime event stream beyond hook-only views

### Local diagnostics

`rawr doctor` checks whether the local environment is ready.

```bash
rawr doctor
rawr doctor --json
rawr doctor --fix --json
```

It reports:

- whether `~/.rawr/config.toml` exists
- resolved DB path and paper/live mode
- whether credentials are discoverable
- whether bundled skills and tool sources are present
- and can create missing bootstrap assets via `rawr doctor --fix` without overwriting an existing config
- when plugin loading looks off, `rawr plugin inspect --json` reports the CLI, MCP, and skill plugin state from one command

## CLI Plugin Contract

RAWR can extend its CLI through the `rawr.cli_plugins` entry-point group. The concrete example package is `examples/rawr_extension_demo`, which registers the `demo-ops` command through that contract. Each plugin entry point should resolve to a `click.Command` or `click.Group`, or to a callable that returns one of those Click objects.

Use `rawr plugin inspect --json` to inspect the current CLI, MCP, and skill plugin state from one command.

Phase 1 is top-level only: plugins may add `rawr <name> ...` commands, but they may not inject subcommands into built-in command trees such as `rawr tool`, `rawr skill`, or `rawr mcp`.

Collision behavior is fail-closed. If a plugin would reuse an existing top-level command name, RAWR rejects that registration instead of silently overriding the built-in command or another plugin. That is distinct from partial failure: import, metadata, and other non-collision errors are recorded as plugin failures while other discovered plugins can still load.

When plugin loading fails, the diagnostic shape preserves these fields:

- `entry_point`
- `value`
- `source_package`
- `version`
- `module`
- `attr`
- `reason`

The trust model is trusted-local-package: RAWR only loads CLI plugins from packages already installed in the current environment. There is no remote marketplace or automatic install step, so only install plugin packages you trust.

## Built-In Skill Catalog

Bundled workflow prompts currently shipped in `skills/`: 16 executable workflows plus the docs-only `financial-report` contract.

| Skill | Role |
| --- | --- |
| `auto-research` | End-to-end stock research workflow |
| `auto-research-batch` | Batch comparison workflow prompt |
| `wallstreet` | Meta-skill for framework-based analysis |
| `goldman` | Multi-factor fundamental screening |
| `dcf` | DCF valuation workflow |
| `bridgewater` | Portfolio and risk analysis workflow |
| `jpmorgan` | Earnings quality workflow |
| `blackrock` | Portfolio allocation workflow |
| `citadel` | Technical analysis workflow |
| `harvard` | Dividend and quality workflow |
| `bain` | Peer and moat analysis workflow |
| `renaissance` | Pattern and anomaly workflow |
| `mckinsey` | Macro impact workflow |
| `sector-analysis` | Theme and sector analysis workflow |
| `quant-research` | Validation-first strategy and backtest review workflow |
| `market-regime` | KR market-regime research workflow |
| `financial-report` | Docs-only shared research report contract |

## MCP Surface

RAWR also exposes an importable FastMCP app:

```python
from rawr.mcp.server import mcp
```

`rawr.mcp.server:mcp` is the documented MCP server entrypoint and a special-case exception to the general `rawr.api` facade guidance. For library code, prefer `rawr.api`; for MCP server wiring, use this documented entrypoint.

Run it from the CLI:

```bash
rawr mcp serve
rawr mcp serve --transport http --host 0.0.0.0 --port 8000 --path /mcp
rawr mcp serve --transport streamable-http
rawr mcp serve --transport sse
rawr mcp health --json
rawr mcp readiness --json
```

`rawr mcp serve` options:

| Option | Meaning |
| --- | --- |
| `--transport` | `stdio`, `http`, `streamable-http`, or `sse` |
| `--host` | Bind host for networked transports |
| `--port` | Bind port for networked transports |
| `--path` | HTTP path for networked transports |
| `--log-level` | Logging level |
| `--no-banner` | Disable FastMCP startup banner |

Additional ops commands:

| Command | Meaning |
| --- | --- |
| `rawr mcp health --json` | Static MCP surface health summary |
| `rawr mcp readiness --json` | Runtime readiness based on config/auth/DB checks |
| `rawr observe summary --json` | Centralized summary across runtime logs, audit, sessions, and readiness |
| `rawr observe tail --json` | Tail structured runtime log records |
| `rawr doctor --fix --json` | Create missing local bootstrap assets, then rerun readiness |
| `rawr audit stream --after-id 0 --json` | Read incremental runtime audit events from the SQLite audit store |

Order-tool governance is shared with the CLI. When an MCP client calls
`place_order`, `modify_order`, or `cancel_order` through `rawr.mcp.server:mcp`,
the request is routed through the CLI policy/session/hooks envelope before the
broker-facing function runs. Confirmation-gated order calls can provide
`policy_ack` as an argument or via MCP metadata at `_meta.rawr.policy_ack`.

### MCP plugin contract

RAWR can extend its MCP tool surface through the `rawr.mcp_plugins` entry-point group. The concrete example package is `examples/rawr_extension_demo`, which registers an MCP tool module through that contract. Each plugin entry point should resolve to a mapping, or to a callable that returns a mapping, with these required plugin fields:

- `name`
- `version`
- `source_package`
- `tool_modules`

`tool_modules` must be a non-empty list of importable module paths. Each listed module can register additional MCP tools using the same `mcp.tool` convention as the built-in modules.

The built-in `rawr.mcp.server:mcp` server entrypoint remains the supported default server wiring. Plugins are an extension layer on top of that surface, not a replacement for it.

Collision behavior is fail-closed. If a plugin would register a tool name that already exists in RAWR, RAWR rejects that collision instead of silently overriding the existing tool.

Loading uses partial failure by default for non-collision errors. A bad entry point, malformed plugin metadata, or an import error in one plugin is recorded as a plugin failure while other discovered plugins can still load. Those failure records preserve the same diagnostic fields:

- `entry_point`
- `value`
- `source_package`
- `version`
- `module`
- `attr`
- `reason`

The trust model is trusted-local-package: RAWR only loads plugins from packages already installed in the current environment. There is no remote plugin marketplace or automatic package installation step. Only install and enable plugin packages you trust.

### Skill plugin contract

RAWR can extend its skill catalog through the `rawr.skill_plugins` entry-point group. The concrete example package is `examples/rawr_extension_demo`, which publishes the `demo-skill` skill through that contract. Each plugin entry point should resolve to a mapping, or to a callable that returns a mapping, with these required plugin fields:

- `name`
- `title`
- `description`
- `market_support`
- `inputs`
- `outputs`
- `requires_tools`
- `safety_level`
- `docs_only`
- `body`

Skill plugins come in two shapes:

- Docs-only plugins set `docs_only: true` and provide markdown content only. They do not declare `runner_kind` or `runner_ref`.
- Executable plugins set `docs_only: false` and must also provide `runner_kind` and `runner_ref`.

`runner_kind` describes how RAWR should execute the skill, and `runner_ref` identifies the importable runner target or callable reference to use for that execution path.

Collision behavior is fail-closed. If a plugin would reuse an existing skill name, RAWR rejects that registration instead of silently overriding the built-in skill or another plugin.

Loading uses partial failure by default for non-collision errors. One bad entry point, malformed skill metadata, or an import error in one plugin is recorded as a plugin failure while other discovered plugins can still load.

The trust model is trusted-local-package: RAWR only loads skill plugins from packages already installed in the current environment. There is no remote marketplace or automatic package installation step, so only install and enable plugin packages you trust.

### MCP plugin compatibility and version policy

MCP plugins are treated as a Phase 1 contract: the current surface is stable enough to use, but it is not a frozen forever-API. Plugin authors should version and document their plugin contract explicitly, and they should pin and test against RAWR versions that they know are compatible.

When RAWR evolves the plugin contract, the change should be documented and versioned so plugin maintainers can update deliberately. Collisions fail closed, so incompatible plugins do not silently override built-in or existing tool names.

### MCP tool modules

RAWR currently ships 116 MCP tools across these modules:

| Module | Tool count | Focus |
| --- | ---: | --- |
| `market_tools` | 7 | Quotes, search, OHLCV, market overview, ETF/ETN lookups |
| `analysis_tools` | 3 | Indicators, screeners, comparison |
| `decision_tools` | 3 | Structured research-only decision workflow, verification, and outcome refresh |
| `portfolio_tools` | 2 | Read-only portfolio book listing and normalized snapshots |
| `quant_tools` | 10 | Risk, signals, scoring, factor ranking |
| `trading_tools` | 12 | Orders, readiness, balance, holdings, P&L, daily broker execution sync |
| `system_tools` | 4 | System status, market hours, watchlists |
| `knowledge_tools` | 19 | Journal, research, memory context, skill proposals, stats, client-order lookup |
| `automation_tools` | 27 | Alerts, schedules, kill switch, trust level, session state |
| `notification_tools` | 3 | Delivery and notification logs |
| `news_tools` | 3 | Disclosures, news, sentiment |
| `framework_tools` | 10 | Wall Street-style framework analysis |
| `backtest_tools` | 3 | Backtest, simulation, walk-forward |
| `macro_tools` | 2 | FRED-backed macro indicator lookups |
| `signal_tools` | 2 | LLM signal aggregation and sentiment |

`check_us_trading_readiness` is read-only. It checks KIS US quote, USD balance,
pending-order, and filled-order endpoints without submitting, modifying, or
canceling any order.

## Typical Workflows

### First-run bootstrap

```bash
rawr init
rawr doctor --fix --json
rawr doctor --json
rawr policy show --json
```

`rawr doctor --fix` is conservative: it creates missing config, DB, policy, session, and env-example artifacts, but it does not overwrite an invalid config or invent credentials.

### Interactive detached sessions

```bash
rawr tool call get_price --arg code=005930 --interactive --json
rawr session presence <session-id> --json
rawr session transcript <session-id> --json
rawr session attach-info <session-id> --json
rawr session token issue <session-id> --owner remote-worker --scope read --scope write --json
rawr session attach-terminal <session-id> --owner cli --print-command
rawr session handoff <session-id> --from-owner cli --to-owner worker --json
```

### Centralized observability

```bash
rawr observe summary --json
rawr observe tail --limit 20 --json
rawr observe export --output observability.json --json
```

`rawr observe` is the first centralized observability surface. It aggregates runtime log records, runtime audit stats, session state, and readiness into one operator-facing CLI surface.

`rawr session attach-info` is the first transport-neutral reattach contract. It exposes whether a session is reattachable plus the attach or inspect command a client should use, instead of assuming tmux-specific behavior up front.

`rawr session token issue` is the first authn/authz step for remote or secondary clients. Tokens currently gate read and write access to session inspection and input surfaces without introducing a hosted control plane yet.

### Manual trading research

```bash
rawr search 삼성전자
rawr price 005930
rawr indicators 005930
rawr rawr-score 005930
rawr factor-score 005930
```

### Knowledge graph enrichment

```bash
rawr graph-link 005930 semiconductor belongs_to --target-type sector
rawr graph-link 005930 memory_chip linked_to --target-type theme
rawr graph-neighbors 005930
```

### Agent-driven research

```bash
rawr tool list --json
rawr tool schema generate_auto_research --json
rawr skill show auto-research --json
rawr skill run auto-research 005930 --arg market=kr --json
rawr skill run quant-research "mean reversion works after costs" --arg code=005930 --arg strategy=mean_reversion --json
rawr skill run market-regime --arg index_code=005930 --arg market=kr --arg timeframe=short-term --json
```

### MCP-based integration

```bash
rawr mcp serve --transport stdio
```

Use this mode when another agent platform or MCP client should call RAWR directly.

## Market Support Matrix

RAWR now exposes market support explicitly in skill metadata and tool schema.

| Surface | Support |
| --- | --- |
| `market_tools`, `analysis_tools`, `automation_tools` | `kr` |
| `trading_tools` | `kr`, `us` |
| `framework_tools`, `news_tools` | `kr`, `us` |
| `quant_tools` | mixed; inspect `rawr tool schema <name> --json` |
| `knowledge_tools`, `notification_tools`, `system_tools` | `global` |
| `auto-research`, `auto-research-batch`, `sector-analysis` | `kr` |
| `wallstreet` and framework skills | inspect `rawr skill show <name> --json` |

Unsupported markets are rejected at CLI runtime instead of silently downgraded.

## Deployment

The recommended deployment model is simple:

- install the Python package once
- provide config and secrets on the target machine
- choose whether the runtime entrypoint is the CLI or the MCP server

### Source deployment

```bash
git clone <your-repo-url>
cd rawr-tools
python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install -e .
mkdir -p ~/.rawr
```

### Package build and checks

```bash
python -m pip install build twine
python -m build
python -m twine check dist/*
python -m pip install rawr-tools
```

Publishing uses the GitHub Actions release workflow with trusted publishing.
See [docs/release-guide.md](./docs/release-guide.md) for TestPyPI and PyPI
release steps.

### PyPI and `pipx` distribution

Recommended public install paths:

```bash
pip install rawr-tools
pipx install rawr-tools
```

This repository is set up for GitHub Actions trusted publishing.
The release workflow builds artifacts on every `v*` tag and publishes them to PyPI.
You can also run the same workflow manually and choose `testpypi` or `pypi` as the target.
Before publishing, the GitHub release workflow reruns the publish-blocking subset of the release verification matrix covering docs/packaging checks, install-profile verification, and the installed example-extension smoke test.

Before the first release:

- create the PyPI project `rawr-tools`
- create the TestPyPI project `rawr-tools`
- add GitHub trusted publishing for this repository in both indexes
- create GitHub Environments named `testpypi` and `pypi`

Suggested release flow:

```bash
python -m pip install --upgrade build twine
python -m build
python -m twine check dist/*
git tag v0.1.0
git push origin v0.1.0
```

After the workflow publishes, verify the install path:

```bash
pipx install rawr-tools
rawr --help
```

### MCP server deployment

```bash
rawr mcp serve --transport http --host 127.0.0.1 --port 8000 --path /mcp
```

Operational guidance:

- keep the MCP process behind a reverse proxy for networked access
- inject secrets through environment variables, not checked-in files
- keep `is_paper = true` by default in shared, CI, or test environments

### Example `systemd` unit

```ini
[Unit]
Description=RAWR MCP Server
After=network.target

[Service]
Type=simple
WorkingDirectory=/opt/rawr-tools
Environment=KIS_APP_KEY=your-app-key
Environment=KIS_APP_SECRET=your-app-secret
Environment=DART_API_KEY=your-dart-key
Environment=KRX_OPENAPI_KEY=your-krx-openapi-key
ExecStart=/opt/rawr-tools/.venv/bin/rawr mcp serve --transport http --host 127.0.0.1 --port 8000 --path /mcp
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
```

## Project Layout

```text
src/rawr/
  cli/        Click CLI entrypoints
  core/       Trading, market, quant, config, and knowledge modules
  mcp/        MCP tool surfaces and server wiring
tests/        Test suite
skills/       Agent-facing workflow prompts and templates
docs/         Reference docs, operations guides, maintenance trackers, and historical specs/plans
```

## Development

Run the standard verification suite before shipping changes:

```bash
ruff check .
pytest -q
```

## Release Verification

Before cutting a release, run the release-facing verification matrix:

```bash
uv run pytest tests/test_install_matrix_smoke.py -v
uv run pytest tests/test_extension_example_package.py -v
# after installing examples/rawr_extension_demo into the test environment:
rawr demo-ops status
```

Build distributable artifacts:

```bash
python -m pip install build
python -m build
```

Implementation roadmap and maintenance references:

- [docs/implementation-roadmap.md](./docs/implementation-roadmap.md)
- [docs/cli-reference.md](./docs/cli-reference.md)
- [docs/mcp-reference.md](./docs/mcp-reference.md)
- [docs/skills.md](./docs/skills.md)
- [docs/operations.md](./docs/operations.md)
- [docs/oss-library-todo.md](./docs/oss-library-todo.md)

## FAQ / Troubleshooting

### Why does `rawr doctor` fail even after `rawr init`?

`rawr init` creates local assets, but it does not invent credentials. If `doctor` still fails, the usual cause is missing `[kis].app_key` / `[kis].app_secret`, missing account configuration, or an unreadable config override.

Common reason-specific hints on current CLI surfaces:

- `missing_credentials`: set `[kis].app_key` / `[kis].app_secret` in `~/.rawr/config.toml`, or use Keychain / process env / `rawr.env` intentionally
- `missing_account_no`: set `[kis].account_no` (for example `12345678-01`)
- `token_failed`: recheck app key/secret validity, market session, and paper/live mode alignment

Check:

```bash
rawr doctor --json
rawr mcp readiness --json
```

### Why does `rawr order ...` not place a real order?

That command is intentionally preview-oriented. The shipped live path is:

```bash
rawr tool call place_order --arg ... --arg confirm=false --arg plan_id=<plan-id> --policy-ack --json
```

### Why does US Kelly sizing fail with `FxRateUnavailable`?

US Kelly sizing uses USD→KRW conversion. Configure `[fred].api_key` in `~/.rawr/config.toml` (or equivalent settings source). Missing key errors are fail-closed by design. FX rates are cached in-process with a default TTL of 300 seconds.

### How are mixed-currency trade stats reported?

`get_trade_stats(target_currency=None)` auto-converts mixed KRW/USD journals to KRW. The response now includes `report_currency` and `auto_converted` so callers can tell when conversion was applied.

### How do I diagnose an operator/runtime issue?

Start with:

```bash
rawr doctor --json
rawr plugin inspect --json
rawr observe summary --json
```

If the summary reports `action-needed`, use `rawr policy explain --kind tool --name place_order --required-mode live-trade --json` to understand the active policy decision, then inspect the relevant event stream with:

```bash
rawr audit list --event-type policy_decision --json
```

### Why did `place_order(confirm=false)` get blocked even though I approved the plan?

Approval alone is not enough. RAWR rechecks:

- plan status
- plan expiry
- approval expiry
- symbol match
- approved quantity
- allowed price bounds

Use:

```bash
rawr plan show <plan-id> --json
```

and inspect the returned state before retrying.

### When should I use `rawr plan trade` vs `rawr plan execute`?

Both commands use the same guarded order submission path. Use `plan trade` when you want the explicit trade-oriented command, or `plan execute` when an agent workflow expects the trade-plan lifecycle verb. Both require explicit quantity and price:

```bash
rawr plan execute <plan-id> --qty <qty> --price <limit-price> --side buy --order-type limit --account <key> --policy-ack --json
```

### My agent integration works locally but fails over HTTP. Why?

`stdio` is the simplest and most reliable mode for local CLI agents. HTTP adds deployment concerns:

- bind host/port
- reverse proxy
- secret handling
- process supervision

Start local first:

```bash
rawr mcp serve --transport stdio
```

Then move to HTTP only if you actually need a networked MCP process.

### Where does RAWR store state?

By default under `~/.rawr/`:

- `config.toml`
- `rawr.db`
- `policy.json`
- `sessions/`

If behavior looks machine-specific, this is usually why.

### Why is a plan created as rejected immediately?

That means the computed metrics failed the current safety gate. The most common causes are:

- non-positive EV after cost
- insufficient sample size
- low confidence

Check the stored `invalidation_reason`:

```bash
rawr plan show <plan-id> --json
```

## License Status

RAWR is licensed under `Apache-2.0`.

See [LICENSE](./LICENSE) for the full text.

## Characteristics and Design Notes

RAWR is opinionated in a few ways:

- async-first internals, even when the CLI surface is synchronous
- human-readable CLI output for trader workflows
- JSON-oriented subcommands for agent and automation workflows
- local-first knowledge storage instead of a mandatory hosted backend
- guarded order handling in the CLI instead of live execution by default
- Korean market bias with partial US support where it is already useful

## Current Limitations

- The package is designed primarily for Korean market workflows.
- US support is still partial. `get_news(market="us")` uses SEC EDGAR filings with a SQLite cache fallback, and selected framework OHLCV workflows now use yfinance-backed US history, but broader market parity is not complete.
- `rawr skill run` still excludes some advanced basket and orchestration workflows beyond the currently wired set.
- `rawr tool schema` includes generated input and response-envelope JSON Schema, but tool-specific response `data` schemas remain generic unless the tool exposes a dedicated model.
- Generalized remote terminal attach beyond local tmux-backed workflows remains stretch work.
- Policy authoring ergonomics and governance templates can be expanded further.
- Managed-service observability and full automation-spec parity remain outside the current core roadmap.

## Safety Notes

- Do not place live credentials on shared machines.
- Keep paper trading enabled unless you intentionally switch to live trading.
- Treat local config and SQLite state as machine-specific operational data.
- Review any automation, alert, or scheduling configuration before connecting live accounts.
