Skip to content
i-hridaysahaPublic

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

FinSight

Forecasts next-quarter Revenue, Operating Income, and Free Cash Flow for 117 US-listed companies, built end-to-end from raw SEC EDGAR filings and FRED macro data — where the hard part is not the model but making the target honest before any model sees it.

License Python

📄 Full write-up: https://www.hridaysaha.com/projects-1/finsight 🔗 Demo: runs locally (FastAPI + Streamlit dashboard); no hosted demo — see Reproduce it.

Results

Five models compared under one leakage-safe rolling-origin protocol, scored on reconstructed levels at the identical company-quarters per target, with per-company MASE (mean absolute scaled error) as the headline metric.

Target Winner MASE Served in production
Revenue LSTM 0.734 LSTM — strongest of four sub-1.0 models
Operating Income LSTM ≈ LightGBM (statistical tie) 1.511 / 1.516 LightGBM — tie broken on explainability
Free Cash Flow Seasonal-naive (t−4) 1.551 Seasonal-naive — unbeaten by every learned model

Reading the numbers. MASE is scaled by each company's seasonal-naive (four-quarters-prior) error on its training window, so MASE < 1 beats that in-sample naive. On the harder evaluation window the naive's own realized MASE sits higher — 1.326 / 1.772 / 1.551 — so a model beats the benchmark by scoring below its target's naive line, not below a flat 1.0 (the Operating Income winners clear 1.772 while still above 1.0).

Data note. Metrics are on real public data (actual SEC/FRED filings), not synthetic. Two honest caveats: the universe carries survivorship bias (present-day listings only), and every figure is a single-seed point estimate (RANDOM_STATE = 0), so close results are indistinguishable, not ordered.

Full five-model leaderboard (served model in bold; n = scored companies / points):

Target (n) Model MASE
Revenue (110 / 880) LSTM 0.734
Prophet 0.890
LightGBM 0.917
XGBoost 0.918
Seasonal-naive (t−4) 1.326
Operating Income (99 / 792) LSTM 1.511
LightGBM 1.516
XGBoost 1.549
Seasonal-naive (t−4) 1.772
Prophet 1.874
Free Cash Flow (106 / 844) Seasonal-naive (t−4) 1.551
Prophet 1.581
LightGBM 1.936
XGBoost 1.975
LSTM 5.156

Five-model leaderboard by target

Source: reports/phase11_leaderboard.csv. Rolling-origin trajectories, residuals, and per-target SHAP: assets/eval/.

Why this is non-trivial

  • Point-in-time restatement leakage. SEC filers restate quarters after the fact, and today's XBRL data exposes only the latest revision. FinSight keeps the as-originally-filed value (earliest filing wins) and pulls revised macro series (GDP, CPI) from FRED's point-in-time archive (ALFRED). A reconciliation check on every ingestion caught this working: P&G's FY2015 quarters land 7.11% off the original annual but within 0.9% of the restated one — the check proved the pipeline reconstructed the figure public at the time, not the revised one.
  • Trees cannot extrapolate. A tree leaf predicts the mean of its training targets, so a revenue level past the training range gets clipped. Each target is modeled as a bounded one-step-ahead change (log-growth for Revenue; asinh-delta for Operating Income / FCF, which cross zero), then reconstructed to a level.
  • Incommensurable model spaces. Prophet forecasts levels; trees and the LSTM forecast a differenced transform. Every prediction is reconstructed to a level and scored on one shared equal-support mask — a quarter enters only if the actual, the baseline, and all five models are finite. No model is ever scored on fewer points than another.
  • Per-target inclusion. A company with clean revenue but unreliable cash-flow coverage is kept for revenue and masked only for cash flow, rather than dropped entirely.
  • An honest negative result. No learned model beats the seasonal-naive on Free Cash Flow, so the naive is what gets served — and the API and dashboard say so.

Approach

Raw ingest → point-in-time normalization → feature engineering → five compared models → evaluation → serving. Ingestion stores immutable SEC/FRED payloads; normalization pivots filings into a company-quarter panel where the leakage defenses live; feature engineering adds filing-date-gated lags, rolling stats, ratios, and macro deltas plus the differenced target; modeling runs five approaches under one rolling-origin backtest and explains the interpretable winner (LightGBM) with SHAP; serving fits the winning model per target, persists it, and exposes it via FastAPI with a Streamlit dashboard as a pure client.

End-to-end architecture: SEC EDGAR and FRED flow through a leakage-safe pipeline into five compared models; the winning model per target is persisted and served behind an API, with the dashboard as its client.

Data

  • Sources: SEC EDGAR (XBRL financial statements, 2012–present) + FRED / ALFRED (point-in-time macro indicators). Built from scratch — no pre-packaged datasets.
  • Universe: 117 US-listed companies, ~13 years, one row per company-quarter.
  • Split: expanding-window rolling-origin, one-step-ahead — to forecast quarter T a model uses only quarters ended before T; any in-fold preprocessing is fit inside the training window only.
  • Leakage handling: as-originally-filed values over restatements; point-in-time macro vintages; Q4 derived as annual minus Q1–Q3; adjacency by fiscal-quarter ordinal, never row position.

Full schema and feature dictionary: DATA.md.

Model

Five approaches, one protocol: seasonal-naive (t−4) baseline (also the MASE benchmark), Prophet (per-company univariate), LightGBM and XGBoost (pooled, differenced target, L1 objective), and a pooled LSTM (within-company sequences, the only model that consumes the ordered sequence). Hyperparameters are tuned once per model on a chronological holdout that never sees the test window. Production picks: LSTM for Revenue, LightGBM for Operating Income (tie with the LSTM broken on explainability — SHAP explains it exactly), seasonal-naive for Free Cash Flow.

Per-phase protocol and tuning detail: MODELING.md.

Evaluation

MASE is primary because it scales each company's error by its own seasonal-naive baseline — comparable across a universe spanning single-digit-million to tens-of-billions in cash flow, where a raw MAE would be dominated by the largest firms and MAPE is undefined where the target crosses zero. Supporting metrics: MAE, RMSE, MAPE (Revenue), MAE-scaled-by-revenue (Operating Income, FCF). Validation is strictly rolling-origin; tuning never touches the test window.

Reproduce it

Targets Python 3.12, uses uv; seed is RANDOM_STATE = 0.

git clone <this-repo> && cd FinSight
uv sync                      # or: pip install -r requirements.txt (pinned)
cp .env.example .env         # set SEC_USER_AGENT (descriptive) + FRED_API_KEY (free)

A fresh clone ships no data or models (data/, models/ are git-ignored, regenerated). Run once, in order — step 1 is rate-limited live SEC/FRED traffic (tens of minutes for the full universe):

uv run python -m finsight.sec.ingest --full && uv run python -m finsight.fred.ingest
uv run python -m finsight.process.build          # -> panel.parquet
uv run python -m finsight.features               # -> features.parquet
uv run python -m finsight.models.evaluate        # baseline + Prophet
uv run python -m finsight.models.trees           # LightGBM + XGBoost
uv run python -m finsight.models.lstm            # LSTM
uv run python -m finsight.eval                   # leaderboard + SHAP -> reports/, assets/eval/
uv run python -m finsight.serve.train            # fit + persist production models -> models/

Serve, then test/lint:

uv run uvicorn app.main:app --reload    # http://localhost:8000  (GET /health, /forecast/{ticker})
uv run streamlit run app/dashboard.py   # http://localhost:8501
uv run ruff check . && for f in tests/test_*.py; do uv run python "$f"; done

Repo map

src/finsight/     Pipeline: sec/, fred/, process/, features.py, models/, eval.py, serve/
  dashboard/      Dashboard client/data/formatting (no modeling imports)
app/              FastAPI service (main.py, schemas.py) + Streamlit entry (dashboard.py)
data/ models/     Raw+processed cache, persisted models — git-ignored, regenerated
reports/          Phase reports + leaderboard CSV (tracked)
assets/           EDA, evaluation/SHAP figures, architecture diagrams (tracked)
tests/            One module per phase, runnable standalone

Limitations & next steps

  • Survivorship bias — the 117-company universe is present-day listings only; delisted firms since 2012 are absent, making results mildly optimistic.
  • asinh scale regimes — the asinh-delta target handles sign changes but places firms of very different scale in different regimes of the same transform; mitigated (values in $M), not removed.
  • One quarter ahead only — multi-quarter would compound reconstruction error.
  • Single-seed point estimates — no seed-variance or forecast intervals; close results are indistinguishable, not ordered.
  • v1 is a correct, reproducible build, not an operated service — no retraining cadence, drift detection, versioning, or monitoring; those are deferred.

Next: confidence intervals + seed-variance, multi-quarter forecasting, as-of-date index membership to remove survivorship bias, MLflow tracking, Docker packaging. Full decision log: DECISIONS.md.

License

MIT © Hriday Saha — see LICENSE.

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages