Metadata-Version: 2.4
Name: chartpipe
Version: 0.1.0
Summary: Chart visualization toolkit for quantitative trading analysis
Home-page: https://github.com/yourusername/chartpipe
Author: Your Name
Author-email: your.email@example.com
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: pandas>=2.0.0
Requires-Dist: numpy>=1.24.0
Requires-Dist: click>=8.0.0
Requires-Dist: matplotlib>=3.7.0
Requires-Dist: mplfinance>=0.12.10b0
Requires-Dist: seaborn>=0.12.0
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# ChartPipe

A professional chart visualization toolkit for quantitative trading analysis. Seamlessly integrates with seamflux CLI and quantpipe via Unix pipes.

**Pipeline contract** (CLI flags, JSON envelope, exit codes, `runs/<runId>/` layout) is defined in the repo root [`rule.md`](../rule.md). ChartPipe uses **`schemaVersion`: 1** on stdout when `--json` is set.

## Features

- 🕯️ **OHLCV Candlestick Charts** - Professional candlestick charts with moving average support
- 📊 **Backtest Visualization** - Equity curves, drawdown analysis, and trade markers
- 📈 **Technical Indicators** - RSI, MACD, Bollinger Bands, and more
- 📉 **Statistical Analysis** - Returns distribution, monthly heatmaps, and data distribution
- 🎨 **Dual Themes** - Dark and light themes for different environments
- 🔌 **Pipeline-Friendly** - JSON output support for seamless integration with seamflux/quantpipe
- 🔄 **Auto-Format Detection** - Automatically recognizes Binance, Polymarket, Uniswap, and generic OHLCV formats

## Installation

### From Source (Development)

```bash
cd chartpipe
pip install -e .
```

### Using requirements.txt

```bash
pip install -r requirements.txt
```

## Quick Start

### Integration with seamflux

```bash
# Fetch data from Binance and generate candlestick chart
seamflux invoke binance fetchOhlcv --pipe -p symbol=BTC/USDT -p interval=1h -p limit=200 | chartpipe ohlcv --stdin

# Generate RSI indicator chart
seamflux invoke binance fetchOhlcv --pipe -p symbol=BTC/USDT -p interval=1h -p limit=200 | chartpipe indicators --indicator rsi --stdin

# Generate returns distribution chart
seamflux invoke binance fetchOhlcv --pipe -p symbol=BTC/USDT -p interval=1h -p limit=500 | chartpipe stats --type returns --stdin

# JSON output (for pipeline chaining) — one line on stdout; parse with jq
seamflux invoke binance fetchOhlcv --pipe -p symbol=BTC/USDT -p interval=1h -p limit=200 | chartpipe ohlcv --stdin --json
# Chart path: .artifacts.chart (relative to cwd unless absolute)
```

### Integration with quantpipe

```bash
# Recommended (rule.md): quantpipe writes equity.csv / trades.csv under runs/<id>/
quantpipe backtest --data btc_history.json --strategy ma_cross --run-dir runs/my-run --json
chartpipe backtest --run-dir runs/my-run --json

# Stdin: pipe quantpipe JSON line that includes artifacts.equity (paths from --run-dir/--run-id)
quantpipe backtest --data btc_history.json --strategy ma_cross --run-dir runs/my-run --json | chartpipe backtest --stdin --json

# View candlestick chart from Binance OHLCV (pipe-friendly raw payload)
seamflux invoke binance fetchOhlcv --pipe -p symbol=BTC/USDT -p interval=1h -p limit=200 | chartpipe ohlcv --stdin
```

**Note:** quantpipe `--json` without `--run-dir` / `--run-id` does not emit `equity.csv`; chartpipe `backtest --stdin` then fails with a clear error—use `--run-dir` on quantpipe or `chartpipe backtest --run-dir`.

## Command Reference

### Global Options

| Option | Description |
|--------|-------------|
| `--version` | Show version and exit |
| `--json` | Machine-readable JSON envelope on stdout (single line; debug on stderr) |
| `-o, --output-dir PATH` | Directory to save generated charts (default: `./charts`). Works as `chartpipe -o DIR <cmd>` or `chartpipe <cmd> -o DIR`. |
| `-v, --verbose` | Debug logs on stderr |
| `--dry-run` | Validate input only; do not write chart files |

### Exit codes

| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | General failure (I/O, plot error, bad args) |
| 2 | Input / schema mismatch |
| 3 | Missing optional dependency (e.g. mplfinance for OHLCV) |

Run `chartpipe --help` for the full epilog.

### Headless rendering

[charts.py](src/chartpipe/core/charts.py) sets `matplotlib` to the **Agg** backend by default so charts run without a display. You may still set `MPLBACKEND=Agg` in the environment if needed.

### `chartpipe ohlcv` - Candlestick Charts

Generate professional OHLCV candlestick charts with optional moving averages and volume.

```bash
# From file
chartpipe ohlcv --data ohlcv.json --title "BTC/USDT" --ma 20 --ma 50 --volume

# From stdin with dark theme
seamflux invoke binance fetchOhlcv --pipe -p symbol=ETH/USDT -p interval=1h -p limit=200 | chartpipe ohlcv --stdin --theme dark

# With multiple moving averages
chartpipe ohlcv --data btc.json --ma 10 --ma 30 --ma 100 --volume
```

**Options:**

| Option | Description |
|--------|-------------|
| `--data PATH` | Path to OHLCV data file (JSON) |
| `--input PATH` | Alias for `--data` |
| `--stdin` | Read data from standard input |
| `--title TEXT` | Chart title (default: "Price Chart") |
| `--volume / --no-volume` | Show/hide volume subplot (default: enabled) |
| `--ma INT` | Moving average period (can be used multiple times, default: 20, 50) |
| `--theme [dark\|light]` | Chart theme (default: dark) |

### `chartpipe indicators` - Technical Indicators

Generate technical indicator charts including RSI, MACD, and Bollinger Bands.

```bash
# RSI indicator
chartpipe indicators --indicator rsi --data btc.json

# MACD indicator
chartpipe indicators --indicator macd --stdin

# Bollinger Bands
chartpipe indicators --indicator bb --data btc.json --theme light

# All indicators combined
chartpipe indicators --indicator all --data btc.json
```

**Options:**

| Option | Description |
|--------|-------------|
| `--indicator [rsi\|macd\|bb\|all]` | Indicator type to generate |
| `--data PATH` | Path to OHLCV data file |
| `--input PATH` | Alias for `--data` |
| `--stdin` | Read data from standard input |
| `--period INT` | RSI period (default: 14) |
| `--theme [dark\|light]` | Chart theme |

### `chartpipe backtest` - Backtest Visualization

Generate comprehensive backtest visualizations with equity curves, drawdowns, and trade markers.

```bash
# Prefer: quantpipe with --run-dir, then chartpipe on same directory or stdin JSON with artifacts
# (see "Integration with quantpipe" above)

# From file (legacy JSON with equity_curve / history)
chartpipe backtest --data backtest_results.json --title "MA Cross Strategy"

# From quantpipe run directory (equity.csv, optional trades.csv, optional summary.json)
chartpipe backtest --run-dir runs/my-run --json
```

**Options:**

| Option | Description |
|--------|-------------|
| `--data PATH` | Path to backtest result file (JSON) |
| `--input PATH` | Alias for `--data` |
| `--stdin` | Read JSON from standard input (quantpipe envelope or legacy) |
| `--run-dir PATH` | Load `equity.csv` / `trades.csv` from a `runs/<id>/` directory |
| `--title TEXT` | Chart title (default: from `summary.json` strategy name or generic) |

### `chartpipe stats` - Statistical Analysis

Generate statistical analysis charts for trading data analysis.

```bash
# Returns distribution
chartpipe stats --type returns --data btc.json

# Monthly returns heatmap
chartpipe stats --type monthly --stdin

# Price distribution
chartpipe stats --type distribution --data btc.json

# All statistical charts
chartpipe stats --type all --data btc.json
```

**Options:**

| Option | Description |
|--------|-------------|
| `--type [returns\|distribution\|monthly\|all]` | Chart type |
| `--data PATH` | Path to OHLCV data file |
| `--input PATH` | Alias for `--data` |
| `--stdin` | Read data from standard input |
| `--title TEXT` | Chart title |

## Data Formats

ChartPipe automatically detects and handles multiple data formats:

### Standard OHLCV Format

```json
[
  {"timestamp": "2024-01-01", "open": 42000, "high": 43000, "low": 41000, "close": 42500, "volume": 1000},
  {"timestamp": "2024-01-02", "open": 42500, "high": 44000, "low": 42000, "close": 43500, "volume": 1500}
]
```

### Binance Format (Auto-detected)

```json
[
  {"t": 1704067200000, "o": "42000.00", "h": "43000.00", "l": "41000.00", "c": "42500.00", "v": "1000.00"}
]
```

### Backtest Result Format

```json
{
  "equity_curve": [
    {"timestamp": "2024-01-01", "equity": 10000, "drawdown": 0, "close": 42500},
    {"timestamp": "2024-01-02", "equity": 10200, "drawdown": 0, "close": 43500}
  ],
  "trades": [
    {"entry_time": "2024-01-01", "exit_time": "2024-01-02", "entry_price": 42000, "exit_price": 43000, "side": "long"}
  ]
}
```

### Supported Field Mappings

| Standard | Binance | Polymarket | Uniswap |
|----------|---------|------------|---------|
| `timestamp` | `t`, `T`, `time` | - | - |
| `open` | `o`, `O` | - | - |
| `high` | `h`, `H` | - | - |
| `low` | `l`, `L` | - | - |
| `close` | `c`, `C` | - | - |
| `volume` | `v`, `V`, `vol` | - | - |

## Output Formats

### Standard Output

```
Chart saved: D:\codebase\seamflux-quant\charts\ohlcv_20260317_130405.png
```

### JSON Output (`--json`)

Stdout is **one JSON object per invocation** (rule.md §4). Chart paths are under **`artifacts`** (relative to current working directory unless absolute).

Single chart:

```json
{
  "schemaVersion": 1,
  "tool": "chartpipe",
  "command": "ohlcv",
  "ok": true,
  "artifacts": { "chart": "charts/ohlcv_20260317_130405.png" },
  "meta": { "startedAt": "2026-03-19T12:00:00.000Z", "finishedAt": "2026-03-19T12:00:01.000Z" }
}
```

`chartpipe indicators --indicator all` / `chartpipe stats --type all` use multiple keys under `artifacts` (e.g. `rsi`, `macd`, `bb`).

**Migration:** older releases used `{"img": "..."}` only; scripts should read `artifacts.chart` (or the specific artifact keys for `all` modes).

## Directory Structure

```
chartpipe/
├── src/
│   └── chartpipe/
│       ├── __init__.py
│       ├── __main__.py
│       ├── cli.py
│       ├── cli_exit.py
│       ├── core/
│       │   ├── __init__.py
│       │   ├── backtest_input.py
│       │   ├── charts.py
│       │   ├── input_data.py
│       │   ├── pipeline_json.py
│       │   └── styles.py
│       └── commands/
│           ├── __init__.py
│           ├── ohlcv.py
│           ├── indicators.py
│           ├── backtest.py
│           └── stats.py
├── tests/
├── requirements.txt
├── requirements-dev.txt
├── pytest.ini
├── setup.py
└── README.md
```

## Tests

```bash
pip install -r requirements-dev.txt
pytest
```

## Requirements

- Python >= 3.10
- pandas >= 2.0.0
- numpy >= 1.24.0
- matplotlib >= 3.7.0
- mplfinance >= 0.12.10b0
- seaborn >= 0.12.0
- click >= 8.0.0

## License

MIT License

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## Changelog

### v0.1.0
- Initial release
- OHLCV candlestick charts with moving averages
- Technical indicators (RSI, MACD, Bollinger Bands)
- Backtest visualization
- Statistical analysis charts
- Dark/light themes
- JSON output for pipeline integration
