Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .claude/settings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
{
"enabledPlugins": {}
"enabledPlugins": {
"frontend-design@claude-plugins-official": true,
"context7@claude-plugins-official": true,
"playwright@claude-plugins-official": true
}
}
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@

All project documentation is in the `planning` directory.

The key document is PLAN.md included in full here:
The key document is PLAN.md included in full below; the market data component has been completed and is summarized in the file `planning/MARKET_DATA_SUMMARY.md` with more details in the `planning/archive` folder. Consult these docs only when required. The remainder of the platform is still to be developed.

@planning/PLAN.md
@planning/PLAN.md
59 changes: 59 additions & 0 deletions backend/CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Backend — Developer Guide

## Project Setup

```bash
cd backend
uv sync --extra dev # Install all dependencies including test/lint tools
```

## Market Data API

The market data subsystem lives in `app/market/`. Use these imports:

```python
from app.market import PriceCache, PriceUpdate, MarketDataSource, create_market_data_source
```

### Core Types

- **`PriceUpdate`** — Immutable dataclass: `ticker`, `price`, `previous_price`, `timestamp`, plus properties `change`, `change_percent`, `direction` ("up"/"down"/"flat"), and `to_dict()` for JSON serialization.

- **`PriceCache`** — Thread-safe in-memory store. Key methods:
- `update(ticker, price, timestamp=None) -> PriceUpdate`
- `get(ticker) -> PriceUpdate | None`
- `get_price(ticker) -> float | None`
- `get_all() -> dict[str, PriceUpdate]`
- `remove(ticker)`
- `version` property — monotonic counter, increments on every update (for SSE change detection)

- **`MarketDataSource`** — Abstract interface implemented by `SimulatorDataSource` and `MassiveDataSource`. Lifecycle: `start(tickers)` -> `add_ticker()` / `remove_ticker()` -> `stop()`.

- **`create_market_data_source(cache)`** — Factory. Returns `MassiveDataSource` if `MASSIVE_API_KEY` is set, otherwise `SimulatorDataSource`.

### SSE Streaming

```python
from app.market import create_stream_router

router = create_stream_router(price_cache) # Returns FastAPI APIRouter
# Endpoint: GET /api/stream/prices (text/event-stream)
```

### Seed Data

Default tickers: AAPL, GOOGL, MSFT, AMZN, TSLA, NVDA, META, JPM, V, NFLX. Seed prices and per-ticker volatility/drift params are in `app/market/seed_prices.py`.

## Running Tests

```bash
uv run --extra dev pytest -v # All tests
uv run --extra dev pytest --cov=app # With coverage
uv run --extra dev ruff check app/ tests/ # Lint
```

## Demo

```bash
uv run market_data_demo.py # Live terminal dashboard with simulated prices
```
6 changes: 2 additions & 4 deletions backend/app/market/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

from .cache import PriceCache
from .interface import MarketDataSource
from .massive_client import MassiveDataSource
from .simulator import SimulatorDataSource

logger = logging.getLogger(__name__)

Expand All @@ -22,12 +24,8 @@ def create_market_data_source(price_cache: PriceCache) -> MarketDataSource:
api_key = os.environ.get("MASSIVE_API_KEY", "").strip()

if api_key:
from .massive_client import MassiveDataSource

logger.info("Market data source: Massive API (real data)")
return MassiveDataSource(api_key=api_key, price_cache=price_cache)
else:
from .simulator import SimulatorDataSource

logger.info("Market data source: GBM Simulator")
return SimulatorDataSource(price_cache=price_cache)
12 changes: 4 additions & 8 deletions backend/app/market/massive_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

import asyncio
import logging
from typing import Any

from massive import RESTClient
from massive.rest.models import SnapshotMarketType

from .cache import PriceCache
from .interface import MarketDataSource
Expand Down Expand Up @@ -34,13 +36,9 @@ def __init__(
self._interval = poll_interval
self._tickers: list[str] = []
self._task: asyncio.Task | None = None
self._client: Any = None # Lazy import to avoid hard dependency
self._client: RESTClient | None = None

async def start(self, tickers: list[str]) -> None:
# Lazy import: only import massive when actually using real market data.
# This means the massive package is not required when using the simulator.
from massive import RESTClient

self._client = RESTClient(api_key=self._api_key)
self._tickers = list(tickers)

Expand Down Expand Up @@ -124,8 +122,6 @@ async def _poll_once(self) -> None:

def _fetch_snapshots(self) -> list:
"""Synchronous call to the Massive REST API. Runs in a thread."""
from massive.rest.models import SnapshotMarketType

return self._client.get_snapshot_all(
market_type=SnapshotMarketType.STOCKS,
tickers=self._tickers,
Expand Down
3 changes: 1 addition & 2 deletions backend/app/market/seed_prices.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,5 @@
# Correlation coefficients
INTRA_TECH_CORR = 0.6 # Tech stocks move together
INTRA_FINANCE_CORR = 0.5 # Finance stocks move together
CROSS_GROUP_CORR = 0.3 # Between sectors
CROSS_GROUP_CORR = 0.3 # Between sectors / unknown tickers
TSLA_CORR = 0.3 # TSLA does its own thing
DEFAULT_CORR = 0.3 # Unknown tickers
6 changes: 5 additions & 1 deletion backend/app/market/simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,10 @@ def get_price(self, ticker: str) -> float | None:
"""Current price for a ticker, or None if not tracked."""
return self._prices.get(ticker)

def get_tickers(self) -> list[str]:
"""Return the list of currently tracked tickers."""
return list(self._tickers)

# --- Internals ---

def _add_ticker_internal(self, ticker: str) -> None:
Expand Down Expand Up @@ -251,7 +255,7 @@ async def remove_ticker(self, ticker: str) -> None:
logger.info("Simulator: removed ticker %s", ticker)

def get_tickers(self) -> list[str]:
return list(self._sim._tickers) if self._sim else []
return self._sim.get_tickers() if self._sim else []

async def _run_loop(self) -> None:
"""Core loop: step the simulation, write to cache, sleep."""
Expand Down
3 changes: 2 additions & 1 deletion backend/app/market/stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import asyncio
import json
import logging
from collections.abc import AsyncGenerator

from fastapi import APIRouter, Request
from fastapi.responses import StreamingResponse
Expand Down Expand Up @@ -51,7 +52,7 @@ async def _generate_events(
price_cache: PriceCache,
request: Request,
interval: float = 0.5,
) -> None:
) -> AsyncGenerator[str, None]:
"""Async generator that yields SSE-formatted price events.

Sends all prices every `interval` seconds. Stops when the client
Expand Down
Loading