Metadata-Version: 2.4
Name: wavedesk
Version: 0.1.1
Summary: WaveDesk — multi-agent market analysis desk: 7 indicators, Monte Carlo, risk-managed trade plans.
Author-email: Utkarsh Sharma <utkarshkviim@gmail.com>
License: MIT
License-File: LICENSE
Keywords: elliott-wave,monte-carlo,technical-analysis,trading,volatility
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Requires-Python: >=3.10
Requires-Dist: anthropic>=0.40
Requires-Dist: fastapi>=0.110
Requires-Dist: numpy>=1.26
Requires-Dist: pandas>=2.0
Requires-Dist: python-dotenv>=1.0
Requires-Dist: uvicorn[standard]>=0.29
Requires-Dist: yfinance>=0.2.40
Provides-Extra: plot
Requires-Dist: matplotlib>=3.8; extra == 'plot'
Description-Content-Type: text/markdown

# WaveDesk

Market-analysis desk for **stocks, oil, gold**, and other assets. Seven analysis
agents (Elliott Wave, EMA, Fibonacci, VWAP, ADX, Price Action/S&R, monthly RSI)
run in parallel and feed a **chief-analyst** synthesizer, on top of a forward
**volatility forecast**, a **Monte Carlo** outcome simulation, **risk-managed
position sizing**, **portfolio context**, and a walk-forward **backtest**.

The math is deterministic and reproducible; **Claude** provides the judgement
calls, anchored to the numbers the engine hands it.

> ⚠️ Decision-support / research tool. **Not investment advice**, and not a
> licensed adviser. Markets are not predictable; all signals require independent
> validation and risk management.

## Install & run (for end users)

WaveDesk runs entirely on your own machine — no server, no shared account.

```bash
pipx install wavedesk        # isolated install, adds the `wavedesk` command
#   or:  pip install wavedesk
wavedesk                     # starts the desk and opens your browser
```

Other commands:

```bash
wavedesk serve --port 9000 --no-open   # just the web server
wavedesk analyze gold --json           # one-shot CLI forecast
wavedesk backtest gold --period 5y     # walk-forward track record
```

**LLM is optional and bring-your-own** — WaveDesk auto-detects, in order:
1. a local **`claude` CLI** (Claude Code subscription) → uses it, free to you;
2. an **`ANTHROPIC_API_KEY`** in your environment/`.env` → uses the API;
3. otherwise the **deterministic engine** — the 7 indicators, Monte Carlo,
   volatility forecast, sizing, portfolio, and backtest all run with no LLM.

So it costs **nothing to run** and needs no account. `matplotlib` (for the CLI
`--plot` chart only) is an optional extra: `pip install "wavedesk[plot]"`.

## How it works

```
 yfinance OHLC ─► ZigZag pivots ─► Elliott rule check ─► Fibonacci targets ─► Claude ─► forecast
   data.py          waves.py          waves.py              waves.py        agent.py
```

1. **Pivots** — a percentage ZigZag filter reduces noisy candles to alternating
   swing highs/lows.
2. **Rules** — the last 6 pivots are tested against the three hard Elliott
   impulse rules:
   - Wave 2 never fully retraces wave 1
   - Wave 3 is never the shortest of waves 1/3/5
   - Wave 4 never overlaps wave 1's price territory
3. **Fibonacci** — retracement and extension levels off the last completed swing
   become concrete price targets.
4. **Claude** (`claude-opus-4-8`, adaptive thinking, structured output) reads all
   of the above and returns a JSON forecast: wave count, direction, target,
   invalidation level, confidence, horizon, and rationale.

Without an API key it still runs, using a transparent rule-based fallback.

## Enabling Claude (optional)

The app runs fine with no setup (a transparent rule-based engine). For much
better wave counts, it can use Claude via one of two backends, chosen
automatically (`WAVEDESK_LLM_BACKEND=auto`):

| Backend | How | Billing |
|---|---|---|
| **Subscription** (`cli`) | Have the [`claude`](https://claude.com/claude-code) CLI installed and logged in | Uses your **Claude Code** usage allowance — no API credits |
| **API** (`api`) | Set `ANTHROPIC_API_KEY` in your environment | Pay-as-you-go **API credits** (separate from a chat subscription) |

```bash
export ANTHROPIC_API_KEY=sk-ant-...   # optional — only for the API backend
wavedesk
```

A `.env` file in the directory you run `wavedesk` from is also read, if you
prefer that to exporting.

`auto` prefers the API when a key is set, otherwise falls back to the `claude`
CLI subscription, otherwise the rule-based engine. Force a choice with
`WAVEDESK_LLM_BACKEND=cli|api` or disable Claude entirely with `WAVEDESK_NO_LLM=1`.
The result card's **Engine** footnote shows which one answered.

> Note: driving an app from the `claude` CLI counts against your Claude Code
> usage limits. Keep it to personal/light use.

## Web UI (recommended)

A warm "commodity desk" web interface: pick an asset, choose the lens, and read
the waves. FastAPI serves both the UI and the JSON API.

```bash
wavedesk                                # → http://127.0.0.1:8000, opens your browser
wavedesk serve --port 9000 --no-open    # pick a port, don't open the browser
```

Open the URL, click **Gold** (or Oil, Bitcoin, S&P 500, …) or type any ticker,
tune the history/candle/swing controls, and hit **Read the waves**. You get a
verdict badge, target & invalidation levels, a hand-drawn chart with the ZigZag
pivots overlaid, the impulse-rule check, and the model's rationale.

## Command line

```bash
# Friendly names: gold, oil, btc, silver, sp500, nasdaq ... or any ticker
wavedesk analyze gold
wavedesk analyze oil  --period 2y --interval 1wk --plot
wavedesk analyze AAPL --threshold 0.04 --json
```

### Options

| Flag          | Default          | Description                                   |
| ------------- | ---------------- | --------------------------------------------- |
| `--period`    | `1y`             | History window (`6mo`, `1y`, `2y`, `5y`, ...) |
| `--interval`  | `1d`             | Candle size (`1d`, `1wk`, `1h`, ...)          |
| `--threshold` | `0.05`           | ZigZag swing size as a fraction (5%)          |
| `--model`     | `claude-opus-4-8`| Claude model id                               |
| `--plot`      | off              | Save a PNG chart with pivots overlaid         |
| `--json`      | off              | Emit raw analysis + forecast JSON             |

## Decision-support layer (for expert review)

Three deterministic modules turn the ensemble's *signal* into decision support.
The methodology is deliberately conservative and auditable:

**Backtest / track record** (`backtest.py`, `/api/backtest`, "Run backtest" button)
- Walk-forward, **no look-ahead**: at each historical date the signal is built
  from data up to that day only, then scored on the forward window.
- **Backtests the deterministic rule consensus + volatility model — not the LLM.**
  The LLM interpretation can only be judged by *forward-tracking* live calls
  (thousands of historical LLM calls are impractical). Treat the numbers as a
  floor/sanity check on the underlying logic.
- Non-overlapping windows (independent samples); **excludes costs/slippage**.
- Reports hit rate, expectancy, win/loss, strategy-vs-buy&hold, **volatility
  calibration** (fraction of realized moves inside the predicted 1σ / 90% band),
  and per-indicator attribution. `wavedesk backtest gold --period 5y`

**Position sizing & risk** (`sizing.py`, `trade_plans` in `/api/predict`)
- **Risk-first, deterministic** (never LLM): `units = (risk% × capital) / |entry − stop|`,
  with the chief analyst's **invalidation as the stop** → bounded loss.
- Confidence scales *within* the risk budget; position also capped by a per-profile
  max weight. Profiles — conservative / moderate / aggressive — set risk-per-trade
  (0.5 / 1 / 2%), max position (10 / 20 / 35%), and minimum reward:risk (2.0 / 1.5 / 1.2).
- Trades below the profile's min R:R are flagged **skip**. Kelly & expected value
  come from the Monte Carlo endpoint distribution.

**Portfolio context** (`portfolio.py`, `/api/portfolio`)
- Correlation-based (Pearson on daily log returns): correlation-to-book,
  diversification score, concentrated-cluster %, effect on portfolio volatility,
  and a suggested max weight that shrinks as correlation rises.

> ⚠️ These make it a **decision-support / research tool**, not a licensed adviser.
> Personalized advice for compensation requires registration (e.g. SEBI RIA/RA,
> SEC/state RIA). Not investment advice.

## Project layout

```
wavedesk/
  data.py        # yfinance OHLC loading + ticker aliases
  waves.py       # ZigZag, Elliott rules, Fibonacci; assembles the 7 indicators
  indicators.py  # EMA, VWAP, ADX, price-action/S&R, monthly RSI (deterministic)
  volforecast.py # forward volatility forecast (EWMA + horizon backtest)
  montecarlo.py  # Monte Carlo path simulation + outcome distribution
  agent.py       # 6 analyst LLM calls + chief synthesizer (+ rule fallback)
  sizing.py      # position sizing & risk profiles (deterministic)
  portfolio.py   # correlation / concentration context
  backtest.py    # walk-forward track record (deterministic layer)
  cli.py         # command-line entry point
  server.py      # FastAPI: serves the UI + JSON API
  static/        # index.html · styles.css · app.js (the web UI)
```

## Tuning the ZigZag threshold

The single most important knob. Too small and you'll label noise as waves; too
large and you'll miss the structure. Daily equities/indices: `0.03–0.05`.
Commodities and crypto (more volatile): `0.06–0.10`. Weekly bars: lower it.
