Metadata-Version: 2.4
Name: rawr-tools
Version: 0.1.2
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: 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-ta>=0.3.14b; 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>=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-ta>=0.3.14b; extra == 'full'
Requires-Dist: pandas>=2.0; extra == 'full'
Requires-Dist: pykrx>=1.0; extra == 'full'
Requires-Dist: setuptools>=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: pykrx>=1.0; extra == 'market-data'
Requires-Dist: setuptools>=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-ta>=0.3.14b; 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)

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

- [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)
- [How To Use RAWR](#how-to-use-rawr)
- [Architecture](#architecture)
- [Examples](#examples)
- [Contributing](#contributing)
- [Security](#security)
- [Roadmap](#roadmap)
- [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)
- [Release Guide](./docs/release-guide.md)

## 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, 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
- 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`
- 80+ MCP tools across market, quant, trading, automation, knowledge, and framework modules
- Discoverable CLI tool contracts through `rawr tool ...`
- Bundled workflow skills through `rawr skill ...`
- Local environment diagnostics through `rawr doctor`

## Requirements

- Python `3.12+`
- 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: `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/rawr_tools-0.1.0-py3-none-any.whl
```

## Dependency Extras

Start with the base install for the core CLI, library, and local storage:

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

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.

### `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.

### `quant`

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

Adds the quant stack used by indicators, scoring, risk, and portfolio analysis flows.

### `full`

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

Installs all runtime extras: `mcp`, `network`, `market-data`, and `quant`.
Use this when you want the broadest supported local runtime and do not need to trim dependencies.

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/`

Provide secrets through environment variables:

```bash
export KIS_APP_KEY="your-app-key"
export KIS_APP_SECRET="your-app-secret"
export DART_API_KEY="your-dart-key"
export RAWR_EDGAR_USER_AGENT="RAWR/0.1.0 contact@example.com"
```

Recommended secret loading order:

1. Keychain
2. `~/.rawr/rawr.env`
3. `/etc/rawr/rawr.env`
4. process environment
5. `~/.rawr/config.toml`

You can also start from the env template:

```bash
cp .env.example ~/.rawr/rawr.env.example
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.
- 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 installation

```bash
rawr --help
rawr init
rawr doctor
rawr mcp health --json
rawr mcp readiness --json
```

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
- `rawr mcp health/readiness` verify the agent-facing surface

### First market checks

```bash
rawr price 005930
rawr search 삼성전자
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

```bash
rawr tool list --json
rawr tool schema get_rawr_score --json
rawr skill list --json
rawr skill show auto-research --json
```

### 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 TradePlanService

db = RawrDB(Path("~/.rawr/rawr.db").expanduser())
db.initialize()
service = TradePlanService(db=db)
```

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

## 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 show <plan-id> --json
rawr plan approve <plan-id> --owner cli --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> \
  --json
```

What happens in this flow:

1. `plan create` computes a trade plan from market data, backtest output, walk-forward output, and plan metrics.
2. `plan show` lets you inspect the stored plan, including probability, EV-after-cost, confidence, and invalidation reason.
3. `plan approve` grants a bounded approval lease.
4. `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
   - 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 four stages:

1. `plan create`
   Market data, backtest output, walk-forward output, and probability metrics become a stored trade plan.
2. `plan approve`
   A human grants an approval lease in the CLI.
3. `tool call place_order ... confirm=false --arg plan_id=...`
   RAWR revalidates the approved envelope before broker submission.
4. 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

## 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.

### 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,
    "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`
- `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

## Roadmap

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

Near-term roadmap:

- strengthen the trade-plan lifecycle beyond the current create/show/approve flow
- expand CLI and MCP examples for semi-auto workflows
- improve US-market parity where contracts are already partially exposed
- keep docs, help text, and runtime behavior aligned

Medium-term roadmap:

- 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/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 |
| `order` | Preview a guarded buy or sell order |
| `plan` | Create, inspect, approve, and execute trade plans |
| `balance` | Print account cash balance |
| `holdings` | Print current holdings |
| `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 |
| `policy` | Show or set the active execution governance mode |
| `hook` | Register and manage runtime hooks around tool and skill execution |
| `doctor` | Check local environment and agent surface readiness |
| `mcp` | Run or manage the packaged MCP server |

## 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
```

### Research Plus Agent Tooling

```bash
rawr tool list --json
rawr tool schema get_rawr_score --json
rawr skill run auto-research 005930 --json
```

### Semi-Auto Trading

```bash
rawr plan create 005930 --strategy mean_reversion --json
rawr plan approve <plan-id> --owner cli --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> --json
```

### Runtime Operations

```bash
rawr doctor --json
rawr observe summary --json
rawr audit list --json
rawr policy show --json
rawr session list --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 approve <plan-id> --owner cli --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> \
  --json
rawr plan execute <plan-id> --json
```

- `rawr plan create` stores a trade plan with adjusted probability, EV-after-cost, and a bounded entry range.
- `rawr plan approve` grants a CLI approval lease tied to the plan expiry window.
- After approval, the shipped live path is `rawr tool call place_order ... --arg confirm=false --arg plan_id=<plan-id> --json`, which revalidates the approved envelope before broker submission.
- `rawr plan execute` exists only as an optional placeholder. In the current build it returns `reason=unsupported` unless a backend implementation is added later.

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
- does not place the order through the CLI
- is intentionally preview-oriented; execution belongs on the MCP side

### `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 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
```

## 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 call get_price --arg code=005930 --output text
rawr tool call get_price --arg code=005930 --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`
- `goldman`
- `dcf`
- `bridgewater`
- `jpmorgan`
- `blackrock`
- `citadel`
- `harvard`
- `bain`
- `renaissance`
- `mckinsey`
- `wallstreet`

Examples:

```bash
rawr skill run auto-research 005930 --arg market=kr --json
rawr skill run auto-research 005930 --arg market=us --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 005930 --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 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 ship as executable workflows
- `docs_only` remains part of the metadata contract for future catalog entries

### 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 heartbeat <session-id> --json
rawr session detach <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
- `logs` reads recent detached-process output from the session log file
- `cancel` marks the stored artifact as cancelled
- `prune` removes old terminal session artifacts while retaining the newest sessions

### 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
- 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

## CLI Plugin Contract

RAWR can extend its CLI through the `rawr.cli_plugins` entry-point group. Each plugin entry point should resolve to a `click.Command` or `click.Group`, or to a callable that returns one of those Click objects.

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.

Loading uses partial failure by default. One bad entry point, malformed Click object, or import error is recorded as a plugin failure while other discovered plugins can still load.

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/`:

| 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 |

## 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 |

### MCP plugin contract

RAWR can extend its MCP tool surface through the `rawr.mcp_plugins` entry-point group. 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.

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. 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 80 MCP tools across these modules:

| Module | Tool count | Focus |
| --- | ---: | --- |
| `market_tools` | 4 | Quotes, search, OHLCV, market overview |
| `analysis_tools` | 3 | Indicators, screeners, comparison |
| `quant_tools` | 10 | Risk, signals, scoring, factor ranking |
| `trading_tools` | 8 | Orders, balance, holdings, P&L |
| `system_tools` | 3 | System status, market hours, watchlists |
| `knowledge_tools` | 13 | Journal, research, graph, strategy memory |
| `automation_tools` | 20 | 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 |

## 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
```

### 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`, `trading_tools`, `automation_tools` | `kr` |
| `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`, `us` |
| `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 index deployment

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

### 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 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
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/         Design notes and implementation plans
```

## Development

Run the standard verification suite before shipping changes:

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

Build distributable artifacts:

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

Implementation roadmap and execution checklist:

- `docs/implementation-roadmap.md`
- `docs/cli-reference.md`
- `docs/mcp-reference.md`
- `docs/skills.md`
- `docs/operations.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`, or an unreadable config override.

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> --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.

### Why does `rawr plan execute` return `reason=unsupported`?

In the current build, `rawr plan execute` is only a placeholder CLI hook. The shipped execution path is still the guarded tool call:

```bash
rawr tool call place_order --arg ... --arg confirm=false --arg plan_id=<plan-id> --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` reports source-level signatures and docs, not a full generated JSON Schema contract.
- More expansive dashboard and UI work described in the design docs remains deferred.

## 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.
