Data Platform, Applied ML
Stockidence
- 11
- Dagster schedules, each on its source's own cadence, from overnight to quarterly
- 12 GB
- DuckDB warehouse in three layers, backed up to S3 every night
- +1.5 pp
- Quarterly top 20 vs the S&P 500 over 26 walk-forward quarters; mostly market exposure (beta 1.6)
Pipeline
01
Ingest
Dagster schedules on each source's cadence plus quarterly and weekly refreshes of every ticker, gated by per-endpoint watermarks
02
Model
DuckDB raw → staging → mart; indicators, yearly-rate fundamentals and point-in-time S&P 500 membership built in the warehouse
03
Rank
XGBoost rank:ndcg, quarterly (a 15-seed ensemble) and weekly, with per-stock SHAP breakdowns
04
Serve
FastAPI + React on one Oracle Ampere box; deploys wait for CI, the warehouse goes to S3 nightly
What it is
Stockidence primarily serves as a host for my stock ranking models as well as some other market related information. The Quarterly model orders 464 stocks by how the model expects them to do against each other for the next three months. The weekly model is similar but at a weekly grain and runs every Friday a ranking for the next week. The news page has a daily summary and weekly article written by a Qwen3.5 locally hosted on my Oracle Cloud instance. Lastly, the Market page collects movers, calendars, macro indicators, and commodities.
How it's changed
Originally my idea was to create a stock prediction model. I quickly found that with my limited data this wasn't very feasible and so instead I turned to working on a stock ranking model. I played around testing all the basic models like linear regression, ridge regression, random forests, and XGBoost. I ended up publishing the first model using XGBoost with the top 20 ranked stocks averaging +4.6 pp/qtr over the S&P 500.
However one thing always bothered me, the model seemed to strongly favor stocks hitting drawdowns and volatility. Then it clicked because the stocks that I had data for were in the S&P 500 currently that also meant that over time they have 'survived'. Thus I had my first experience with survivorship bias. To fix this issue I ran ticker backfills on stocks that were previously in the S&P 500 but have since been removed. This amended the issue whilst simultaneously obliterating my top 20 ranked stocks average down to a measly +0.2 pp/qtr over the S&P 500.
Now I was again back to square one. So I began testing various different adjustments like ensembling, tree depth, data processing, and feature engineering. One training seed could move the result by over a point, so I changed the model to instead average 15 seeds into one ranking. I also split the lead into beta and alpha. The model now leads the S&P by +1.50 pp/qtr, but with a beta of 1.58 and alpha around zero: it buys volatile stocks that rise more than the market in good quarters and fall more in bad ones. Over 26 quarters, a lead would need to be about 4 pp/qtr to count as significant, which free data on S&P 500 stocks isn't likely to produce. So I kept the model and published those numbers instead of chasing a better-looking one.
Additionally, there have been other hiccups such as model retrains causing the website to not load data for hours and API providers removing APIs from their free tier leaving me with a bunch of red jobs. To fix the DuckDB lock I implemented an API fallback to a daily snapshot on S3. I also implemented a Dagster concurrency pool to keep jobs from failing during long trains that overlap with schedules. Some endpoints I lost permanently like the Alpha Vantage news & sentiment API which I haven't found an adequate successor to while others I have been able to migrate to other platforms or derive in pipeline.
Ingestion
Market-wide data arrives on Dagster schedules, each on its source's own cadence, mostly to stay under Alpha Vantage's very small free-tier quota: news twice a day and overnight, movers after each session, IPO and earnings calendars on weekdays, the tracked companies' 8-K filings and Fed, BLS, SEC, and FTC releases each weekday morning, VIX and S&P 500 levels daily from FRED, and macro indicators, commodities, the symbol listing, and the S&P 500's membership history monthly.
Per-ticker data (prices, financials, company profiles) is refreshed for the whole universe before each retrain: once a quarter, and every Friday with prices forced through so each ticker lands that day's close. Every fetch goes through a staleness gate keyed on (source, ticker, endpoint), with a watermark per combination, so each run pulls only what has actually gone stale:
- Prices: continue from each ticker's own high watermark (Twelve Data, split-adjusted), never a full re-download
- As-reported financials: no clock at all. The gate works out the latest period that should exist from SEC filing deadlines and only refetches if the warehouse is behind it
- Balance sheets Finnhub serves empty: filled from SEC EDGAR, matched to the same filing by accession number
- Profiles and other fundamentals: fixed TTLs ranging from days to months
- Failures: each fetch retries three times, then is recorded and skipped, so one bad symbol can't stall a multi-hour run
Warehouse
A single DuckDB file (about 12 GB) holds three layers. Raw lands provider responses as-is, staging unnests and types them, and mart holds the aggregates, model inputs, and published rankings. The website never talks to a provider directly; it only reads the warehouse through the API.
Anything that can be computed is not fetched. MACD is a premium Alpha Vantage endpoint, so it's derived in the mart layer from EMA12 and EMA26. The same goes for every technical indicator (SMA, EMA, RSI, STOCH, ADX, CCI, AD, OBV, ATR, BBANDS) and the rolling volatility and drawdown stats, which are Dagster assets downstream of the cleaned daily bars.
Three modeling problems took the most thought. As-reported financials arrive as raw XBRL tags that aren't standardized across companies, so the mart layer maps them to canonical metrics with alias and prefix matching plus coalesce fallbacks. Quarterly filings report income and cash flow for the fiscal year to date (a Q3 filing holds nine months), so each filing's flows are scaled to a yearly rate by the span they cover, and ROE means the same thing in every quarter. And because one news article mentions several tickers and each ticker appears in many articles, sentiment is stored at the article level with a junction table carrying per-ticker relevance and sentiment scores.
The ranking models
The quarterly model is XGBoost with a rank:ndcg objective. It doesn't predict prices or returns; it orders each quarter's cohort so the top of the list beats the bottom. Inputs are 13 raw point-in-time features from each quarter's end-of-quarter snapshot: trend and momentum (price vs SMA200, 3- and 12-month returns, distance from the 52-week high), risk (252-day volatility, max drawdown, ATR %), and balance-sheet quality (ROE, ROA, debt/equity, current ratio, cash and free cash flow to assets). A 40-feature engineered variant halved the rank IC, so I kept the simpler set.
It trains on every finished quarter since 2012: 20,870 rows across 544 stocks, each stock counted only for the quarters it was actually in the S&P 500. Every fit is 15 models with different random seeds, and a stock's score is their average. One seed's top 20 shares only two thirds of its names with another seed's; two 15-seed ensembles share 92%. I also tested tree depths 1, 2, 4, and 6 against the current 3, with 15 to 45 seeds each. Shallower trees lose clearly, and deeper ones overfit as single models and don't beat depth 3 by more than seed noise as ensembles.
The weekly model uses the same 13 inputs plus two short-term ones: last week's move against its sector, and the past year's return without its latest month. It retrains every Friday on 282,391 stock-weeks and publishes a list held from Monday's open to Friday's close.
Validation
Walk-forward backtests with no lookahead. For every quarter from 2019 to mid-2025, the quarterly model trains only on earlier snapshots and is graded on that quarter's returns: 26 out-of-sample quarters and 10,780 stock-quarters. The weekly model refits once a quarter and ranks the next 13 weeks: 411 weeks. Both are measured against the S&P 500 and against the whole ranked list, with beta and alpha from a fit on the index, because a volatile list beats the index in rising markets without any skill.
- Quarterly top 20 vs S&P 500
- +1.50 pp/qtr (t = 0.7), ahead in 46% of quarters
- Quarterly top 20 vs the whole list
- +2.37 pp/qtr (t = 1.3)
- Quarterly beta / alpha
- 1.58 / −0.66 pp/qtr
- Quarterly rank IC, within each quarter
- +0.024 (t = 0.65; random = 0)
- Quarterly precision@10
- 11.5% (random 2.4%)
- Weekly top 10 vs S&P 500
- +0.15 pp/week, ahead in 50% of weeks
- Weekly top 10 vs the whole list
- +0.19 pp/week (t = 0.97)
- Weekly beta / alpha
- 1.72 / −0.06 pp/week
Scheduled retrains
At 03:00 UTC on the first day of each quarter, one Dagster job runs the whole chain: an incremental refresh of every ticker, a rebuild of the training and scoring datasets, a re-execution of the production notebook to refit the model, and publication of the new ranking with its SHAP contributions, input weights, track record, and ranking-quality metrics. Those metrics used to exist only in the notebook's printed output, inside a container that every deploy recreates; each run now records them in the warehouse, which also makes runs comparable. Every Friday at 17:30 New York time a second job does the same on a weekly grain and grades the previous week's list. Each has a twin that skips the refresh, for when the data is already fresh.
The jobs are defensive about bad data. If fewer than half of a typical cohort has fresh prices, the job fails loudly and leaves the current rankings live instead of publishing a thin or stale list. Undersized cohorts are dropped from grading, and stale tickers and failed endpoints are logged so the cause shows up in Dagster.
Those guards caught a real bug. Landing prices for one ticker was bumping the watermark of every ticker in the table, so the staleness gate skipped nearly the whole universe: in production, 3 of 525 tickers got fresh prices. The fix scoped watermark updates to the rows actually landed and added a resync that rebuilds every ticker's watermark from the data itself.
News summaries
The News page has a one-paragraph summary each weekday morning and a long article on Saturdays, written from the full text of the articles by Qwen3.5-4B running in Ollama on the same box. The stories come from the tracked companies' 8-K filings and from Fed, BLS, SEC, and FTC releases.
Code chooses the stories, fetches and checks the text, and plans each piece; the model only turns the facts it's given into sentences, and every summary lists its sources. The model loads only while a summary job runs, so it never holds memory during a retrain.
Serving and explainability
A plain-Python service layer over DuckDB is wrapped by a typed, read-only FastAPI surface: both rankings, per-stock detail, the model overviews, the news summaries, and the market data. The React + TypeScript frontend consumes it with TanStack Query.
Every retrain exports per-stock SHAP contributions that sum exactly to the model's score. Each stock page uses them to show "how the model got here": every input's value next to the cohort median and how much it moved the score, with a plain-English verdict. The method pages show the input weights, the track record by quarter or year, beta and alpha, and the latest run's ranking-quality metrics, so the claims on the site can be checked against the evidence.
Deployment
The whole stack (FastAPI, the Dagster webserver and daemon, Ollama, and the SPA behind nginx with HTTPS via certbot) runs under Docker Compose on a single always-free Oracle Cloud Ampere A1 instance with 2 OCPUs and 12 GB of RAM. The warehouse is a mounted volume, so deploys can't overwrite it, and the Dagster UI is bound to localhost and reached over an SSH tunnel.
SSH is open to one admin IP, which rules out push-to-deploy from GitHub Actions. Instead the box deploys itself: a lock-guarded cron script runs every five minutes, fast-forwards to master, and rebuilds and health-checks only when the commit has changed. It deploys a commit only after CI has passed for it, and holds while a Dagster run is in progress, since recreating the containers would kill it.
Every night at 03:15 New York time a job writes a compacted, verified copy of the warehouse and uploads it to S3, keeping 14 daily, 8 weekly, and 12 monthly copies. The health endpoint reports the latest backup's age, and one command restores the box or fills a laptop.