stock-scraper / code_wiki.md
sbasu2512's picture
introduce reset functionality
818711d
|
Raw History Blame Contribute Delete
15.2 kB
# Codebase Call Stack and Developer Guide
This repository runs an NSE stock-signal lifecycle: collect market candles, derive features, score each NSE symbol, resolve predictions after future sessions are available, measure quality, and flag model deterioration. It also embeds a separate HTML scraping service. SQLite is the operational source of truth; Parquet holds disposable derived features.
## 1. Runtime entry points
| Entry point | Responsibility |
| --- | --- |
| `uvicorn app.main:app` | Starts FastAPI, JSON endpoints, dashboard, embedded scraper lifecycle, and (via that lifecycle) the in-process scheduler. |
| `python -m jobs.scheduler` | Starts the independent weekday APScheduler process. Docker Compose uses this mode. |
| `python -m jobs.daily_pipeline` | Runs all five production stages in separate subprocesses. |
| `python -m jobs.market_ingestion` | Syncs ticker registry, downloads OHLCV, and rebuilds feature artifacts. |
| `python -m jobs.daily_prediction` | Scores the current IST date and writes prediction rows. |
| `python -m jobs.resolve_predictions` | Resolves mature predictions from future NSE candles. |
| `python -m jobs.calculate_metrics` | Persists metrics for the latest model's last 20 resolved dates. |
| `python -m jobs.check_retrain_trigger` | Compares the persisted precision to the fixed baseline and creates a retrain flag when needed. |
`app.config.Settings` reads environment variables and resolves model/metadata paths from Hugging Face. `database.init_db.init_db()` is idempotently called during API import and by the scheduler before scheduled work. The SQLite helpers in `database.connection` provide dict-shaped rows, transactions, foreign keys, WAL mode, and date conversion.
## 2. Startup and shutdown call stack
```text
uvicorn app.main:app
-> import app.main
-> load_dotenv()
-> database.init_db.init_db()
-> construct FastAPI(lifespan=app.main.lifespan)
-> include API routers
-> app.main.lifespan()
-> jobs.market_ingestion.sync_static_tickers(...)
-> scrapper_service.api.lifespan()
-> create/migrate scraper SQLAlchemy tables
-> load configured scraper sources/stocks/macro sources
-> ensure Playwright Chromium is installed
-> jobs.scheduler.start_scheduler()
-> schedule jobs.daily_pipeline.run_pipeline() Mon-Fri 16:00 IST
-> on shutdown: stop_scheduler() -> scrapper_service.workers.stop_workers()
```
In Docker Compose, the `scheduler` container separately runs `jobs.scheduler`; do not also rely on the embedded scheduler unless duplicate scheduling is intended.
## 3. HTTP API map
All state-changing stock-pipeline routes require header `X-Pipeline-Guid`, checked by `api.auth.require_pipeline_guid` against `PIPELINE_ADMIN_GUID`. Read-only routes do not. The scraper has a `verify_auth` helper for `X-Auth-Token` / `BACKEND_AUTH_TOKEN`, but `POST /action` does not currently attach it as a FastAPI dependency; treat that endpoint as unauthenticated unless protection is added.
| Endpoint | Handler and call stack | Result |
| --- | --- | --- |
| `GET /health` | `app.main.health` | Basic process liveness JSON. |
| `POST /predict?prediction_date=` | `app.main.predict` -> ingestion/rebuild as needed -> `jobs.daily_prediction.run_daily_prediction` | Protected manual prediction/catch-up for one NSE date. Details below. |
| `GET /market/tickers` | `api.market.get_tickers` -> `market_repository.list_tickers` | Registered market tickers. |
| `GET /market/ohlcv` | `api.market.get_ohlcv` -> `market_repository.list_ohlcv` | Filtered candles by symbol, market, date, and limit. |
| `POST /market/tickers` | `create_ticker` -> `upsert_ticker` | Create/update a ticker definition. |
| `PATCH /market/tickers/{id}` | `patch_ticker` -> `update_ticker` | Update supplied ticker fields. |
| `DELETE /market/tickers/{id}` | `remove_ticker` -> `delete_ticker` | Delete a ticker; foreign-key cascade deletes candles. |
| `POST /market/tickers/sync` | `sync_tickers` -> `sync_static_tickers` | Load NSE, US, and context tickers from `static_data`. |
| `POST /market/ingest` | `ingest` -> `ingest_market_data` | Download/upsert market data; does not itself rebuild features. |
| `GET /metrics/twenty-day` | `get_20_day_metrics` -> `fetch_resolved_rows` -> `evaluation.metrics.calculate_metrics` | Live 20-date evaluation, or `insufficient_data`. |
| `GET /retrain/status` | `retrain_status` -> `get_pending_flag` | Current pending retrain flag. |
| `POST /retrain/flags/{id}/acknowledge` | `acknowledge` -> `acknowledge_flag` | Mark a pending flag acknowledged. |
| `POST /retrain/flags/{id}/resolve` | `resolve` -> `resolve_flag` | Close an open retrain flag. |
| `GET /scheduler/status` | `scheduler_status` | Declares intended pipeline order and current IST time. |
| `POST /scheduler/run-now` | `run_now` -> FastAPI `BackgroundTasks` -> `run_pipeline` | Runs full pipeline only when `ALLOW_MANUAL_PIPELINE=true`. |
| `POST /scheduler/resolve-now` | `resolve_now` -> background `run_resolution_job` | Queue resolution alone. |
| `POST /reset/purge-predictions` | `purge_predictions` -> `PredictionRepository.delete_all_predictions` | Permanently clears `predictions`. |
| `POST /reset/rebuild-preds` | `rebuild_preds` -> `jobs.rebuild_predictions.rebuild_predictions` | Scores every distinct `ohlcv.trading_date`; does not purge first. |
| `GET /resolution-status` | `dashboard.resolution_status` | Progress counts and last resolution job state for polling. |
| `GET /dashboard` | `dashboard.dashboard` plus helper functions | Server-rendered prediction, resolution, and calibration dashboard. |
| `POST /action` | `scrapper_service.api.action_router` -> `scrapper_service.actions.ACTIONS[action]` | Scraper worker/data handoff dispatcher, described in section 9. |
## 4. Single-date prediction flow
`POST /predict` is deliberately conservative.
```text
app.main.predict(date)
-> reject weekend or future IST date
-> query predictions for cached date
-> return cache when found
-> check `ohlcv` candle and `merged_features` date
-> if either missing:
sync_static_tickers()
ingest_market_data(end_date=date)
if still no NSE candle: return not_a_trading_day
rebuild_feature_stores()
-> verify NSE `ohlcv` candle again (holiday authority)
-> run_daily_prediction(pd.Timestamp(date))
-> serialize ranked DataFrame response
```
`run_daily_prediction` calls `FeatureEngine.build_features_for_date`, which reads `merged_features.parquet`, filters it to the date, and verifies all metadata-required model columns exist. It then constructs `Predictor(settings.MODEL_PATH, settings.METADATA_PATH)`, calls `Predictor.predict`, calls `inference.rank.rank_predictions`, and writes rows through `PredictionRepository.insert_predictions`.
Prediction inserts contain model file mtime as `model_version`, the feature version, timestamp, symbol, native-model probability, rank, target contract, and closing price. The unique key `(prediction_date, symbol, model_version)` makes repeated requests idempotent for the same model.
### Native XGBoost inference
`inference.predict.Predictor` loads the model with:
```python
booster = xgb.Booster()
booster.load_model(str(model_path))
```
`Predictor.predict` orders feature columns exactly as `model_metadata.json`, converts them to float32, replaces NaN/infinity values, builds `xgb.DMatrix`, and calls `Booster.predict`. For the binary logistic model this returns `P(y=1)` directly. Do not replace this with `XGBClassifier.predict_proba()` for this native-Booster model: an uninitialised sklearn wrapper may not know the class ordering.
## 5. Market ingestion and feature construction
```text
jobs.market_ingestion.main
-> sync_static_tickers() [first run only]
-> ingest_market_data(conn)
-> list active market_tickers
-> fetch yfinance history from first missing date (or 800-day initial lookback)
-> validate OHLC values and volume
-> market_repository.upsert_ohlcv()
-> route each ticker into ohlcv/nifty_ohlcv/india_vix_ohlcv/
us_stocks_ohlcv/macro_ohlcv
-> jobs.rebuild_feature_stores.rebuild_feature_stores()
```
`rebuild_feature_stores` uses SQLAlchemy read connections to load active candles from `all_market_ohlcv`. `_load_candles` divides them into NSE, US, NIFTY, India VIX, and macro groups. It applies:
- `training_transforms.ohlcv` to NSE and US candles (price, momentum, volatility, volume, and candlestick features);
- `training_transforms.nifty` to NIFTY;
- `training_transforms.vix` to India VIX;
- `training_transforms.macro` to Gold, Brent, and USD/INR.
`ParquetFeatureStore.replace` atomically writes the five source feature frames beside the SQLite database. `FeatureEngine.build_all_features` then calls `_merge`: it starts with NSE rows, aligns NIFTY/VIX/macro/US context with backward-looking `merge_asof`, converts US per-symbol features to a wide frame with `build_us_wide`, and adds rolling correlation features through `add_correlation_features`. The result is atomically saved as `merged_features.parquet`. `_build_labels` also writes `training_labels.parquet` using D+1 open and the next five closes.
The underlying tables are not interchangeable: `ohlcv` is the canonical NSE prediction calendar; other table families provide context. The legacy `market_ohlcv` remains only as a migration source.
## 6. Historical prediction rebuild and reset
```text
POST /reset/purge-predictions
-> PredictionRepository.delete_all_predictions()
-> DELETE FROM predictions
POST /reset/rebuild-preds
-> rebuild_predictions()
-> SELECT DISTINCT trading_date FROM ohlcv ORDER BY trading_date
-> read merged_features once
-> validate metadata feature columns once
-> load native Predictor once
-> for every OHLCV trading date:
filter features for date
Predictor.predict -> rank_predictions
_rows_for_date -> insert_predictions
```
The rebuild reports the first/last date, number of OHLCV dates, processed dates, skipped dates with no feature rows, and inserted rows. Run purge first when a complete replacement is wanted; otherwise existing unique-key rows are retained and only missing rows insert.
## 7. Scheduled production lifecycle
`jobs.scheduler.start_scheduler` registers `run_pipeline` at 16:00 IST, Monday through Friday, with one concurrent instance, coalescing, and a 30-minute misfire grace period.
```text
run_pipeline()
-> skip weekends
-> for each STAGES item, run_stage(name, module)
-> start_job_run(...)
-> subprocess: python -m <module>
-> finish_job_run(success/failure)
-> stop immediately if stage fails
market-data -> jobs.market_ingestion
prediction -> jobs.daily_prediction
resolution -> jobs.resolve_predictions
metrics -> jobs.calculate_metrics
retrain-check-> jobs.check_retrain_trigger
```
Subprocess stages isolate memory and failures. `job_runs` records orchestration runs; resolution additionally updates progress while processing individual prediction rows.
## 8. Resolution, metrics, and retrain decision
### Resolution
`run_resolution_job` obtains a SQLite lease using `job_lock_repository.acquire_job_lock` so only one resolver runs. It finds `predictions.resolved_at IS NULL`, then `resolve_pending_predictions` fetches up to `target_horizon_days` future NSE candles for each symbol. `jobs.resolver.resolve_prediction_rows` uses D+1 open as entry, evaluates the next five closes, calculates maximum close/return/label using `target_threshold`, and returns no resolution until enough future sessions exist. The repository writes entry/evaluation values, actual return/label, and `resolved_at`.
### Metrics
`metrics_repository.fetch_resolved_rows` selects resolved predictions for the latest model and its most recent 20 prediction dates. `evaluation.metrics.calculate_metrics` computes threshold precision, PR-AUC, hit rate/positive rate, average return, and probability deciles. `save_metrics_snapshot` upserts the result in `prediction_metrics` keyed by model and date window.
### Retrain flag
`jobs.check_retrain_trigger.main` requires `BASELINE_PRECISION`. With at least 20 resolved prediction days, it calls `evaluation.retrain_trigger.evaluate_retrain_trigger` to compare current precision against the baseline using `RETRAIN_DETERIORATION_THRESHOLD` (default 0.15). It creates one pending `retrain_flags` row when deterioration warrants it; it never retrains automatically.
## 9. Embedded scraper service
The scraper is operationally separate from model prediction. Its data model and helpers live under `scrapper_service` and are managed with SQLAlchemy. At startup it migrates/loads source registries. `POST /action` uppercases `ActionRequest.action`, looks it up in `ACTIONS`, and invokes one handler:
| Action | Handler outcome |
| --- | --- |
| `START` / `SHUTDOWN` | Start or stop scraper, stock-enrichment, and macro worker threads as a group. |
| `GET_RAW_HTML`, `GET_RAW_BULK` | Read queued raw HTML records for a downstream consumer. |
| `DELETE_RAW_HTML`, `DELETE_RAW_BULK` | Remove handed-off raw HTML records. |
| `ADD_SOURCES` | Add a news source. |
| `HEALTH_CHECK` | Report worker and database health. |
| `GET_STATS` | Return scraper database statistics. |
`workers.py` owns thread lifecycle and periodic fetching. `db_helpers.py` persists source records and raw HTML. These records are not consumed by the OHLCV/prediction pipeline shown above.
## 10. Persistence ownership
| Store | Owner and important contents |
| --- | --- |
| SQLite `predictions` | Operational prediction, resolution, and model provenance rows. |
| SQLite `ohlcv` | NSE candles; prediction calendar and resolution source. |
| SQLite context OHLCV tables | NIFTY, VIX, US, and macro input candles. |
| SQLite `job_runs`, `job_locks` | Pipeline/resolution observability and concurrency lease. |
| SQLite `prediction_metrics`, `retrain_flags` | Evaluation snapshots and human workflow state. |
| Parquet feature store | Rebuildable `*_features`, `merged_features`, and `training_labels` artifacts next to the database. |
| Scraper SQLAlchemy database | Source registries and raw HTML, managed independently under `scrapper_service`. |
## 11. Operational rules and debugging order
1. Ensure `DATABASE_URL`, `PIPELINE_ADMIN_GUID`, model access/configuration, and static ticker CSVs are available.
2. Run/schedule market ingestion before prediction; `merged_features.parquet` must match the raw data and model metadata.
3. Use `POST /predict` for a single safe catch-up date. It refuses weekends, future dates, and no-candle holidays.
4. For a complete historical prediction replacement: call `/reset/purge-predictions`, then `/reset/rebuild-preds`.
5. Wait until each prediction has enough future NSE sessions before expecting it to resolve; then run the resolver.
6. Metrics and retrain checks are meaningful only after enough resolved rows/dates exist.
7. Inspect `job_runs`, `/resolution-status`, logs, and the dashboard before changing data. Feature files are derived and can be rebuilt; SQLite prediction history is operational data.