← All posts

Kestrel: Quantitative Research for Daily Stock Selection

Kestrel is a personal project in development. It is private, it is not released, and nothing in this post is investment advice. I am writing about it now because much of its tooling exists to answer one question, whether a stock ranking carries any information at all. So far I have no evidence that it does.

That is the first limit. The others: the system is in paper trading on a broker paper account, its own honesty check, which gates real money, fails today, and the stock universe was picked with hindsight, so every backtest is an upper bound. I report no performance figures here, and I will not.

In short

  • Kestrel is a private daily stock-ranking system in paper trading, and I have no evidence yet that its ranking carries information.
  • Its research tooling counts every trial in an append-only log and judges results with walk-forward tests, the deflated Sharpe ratio, the probability of backtest overfitting, shuffled-label controls and a one-look holdout.
  • The stock universe was picked with hindsight, so every backtest is an upper bound, the holdout is unused, and the honesty check that gates real money fails today.
  • If you test trading ideas of your own, the checklist below, "A checklist for any backtest", lists eight steps you can apply to any backtest.

What problem I wanted to look at

Every day, Kestrel ranks a universe of liquid US stocks against each other, holds the top few in equal weight, and places market-on-open orders through Interactive Brokers. That is cross-sectional stock selection: the question is which stocks look better than the others, not where the market goes.

I built it for two reasons. I wanted a small system that runs unattended every day, with every step recorded, so that I could learn what it takes to run one properly. And I wanted a research setup that is hard to fool. Retail backtesting tools make it easy to try fifty ideas and report the one that worked. My working assumption is that the likeliest answer to "does the ranking carry information?" is no, and the tooling exists to give that answer early and cheaply.

Architecture

The flow is a chain of short jobs that meet in files, so any step can be rerun safely. Python does research, models, daily targets and the execution loop. Rust holds the data types, the file formats, the config and the order plan with every risk rule, which Python calls through PyO3. Rust also supplies an IBKR bar-ingest binary and a simulator binary. Order transmission goes through ib_async in Python, while the order plan and the risk rules that decide what may be sent are Rust.

Kestrel daily pipeline: bars, features and ranking, targets file, Rust order plan and risk rules, then Python execution, broker, reconcile and ledger Evening, Python Adjusted bars daily, from Yahoo Features and ranking Targets file weights per stock Order plan, risk rules (Rust) Next day, before the open Execute ib_async, Python IB Gateway market on open Reconcile fills, drawdown Ledger append-only Kill switch is read before every order; every run is journalled
Figure 1. The daily loop. The evening jobs write a targets file; the next-day job turns it into an order plan, checks it against the risk rules, and sends market-on-open orders.

Data, features and ranking

Live data are daily adjusted bars downloaded from Yahoo. A Rust ingest crate for IBKR bars exists and is tested but is not in the schedule. For each stock the features are momentum over several windows, volatility, trend and distance from the high, each turned into a cross-sectional percentile rank per date. The label is the forward return from the next open, converted to a centred cross-sectional rank. Models are a ridge baseline first and a regularised LightGBM only if it beats ridge.

One timing rule is shared by the backtest, the targets and the engine: weights decided from data up to the close of day t are executed at the open of day t+1 and earn the open-to-open return after that. Tests enforce that no feature at a date changes when later dates are removed, and that targets generated live equal the research weights for the same date.

Portfolio construction and rebalancing

The portfolio is equal weight in the top k scores. The research default rebalances weekly. The paper-test setup is deliberately different: momentum only, a top few kept while they stay inside a slightly wider rank band, and a quarterly rebalance with catch-up for a missed one. Orders go out on rebalance days only; on other days the system only sells names that left the book. The reason is arithmetic: the paper setup trades whole shares, and the broker's minimum commission makes a small order expensive relative to its value.

Risk checks and execution

The Rust plan sizes target shares as the floor of weight times capital over the last close, sells before buys, and skips adjustments under a minimum order size. The risk rules do two different things. They clamp aggressive inputs (a weight above the per-stock cap, gross exposure above one, so no leverage). They abort suspicious ones: stale targets or prices, unknown symbols, negative weights, turnover above a cap, or a single buy above an order cap. An aborted run sends nothing, and keeping yesterday's portfolio is the safe default. Targets that name too few stocks, or whose weights sum to too little, also abort.

[risk]
max_weight     = 0.15  # per stock
max_gross      = 1.0   # no leverage
max_turnover   = 1.2   # sum of |weight change| per rebalance
max_targets_age_days = 4   # targets must be recent
max_bar_age_days     = 5   # so must the prices used for sizing
min_target_names     = 4   # an empty file must never sell the book
max_price_gap  = 0.25  # drop a symbol on a possible split

These are keys from the research-default config file, trimmed; the paper-test file sets its own values. Both languages read the same config files, so a limit cannot drift between research and execution.

Scheduling

A local scheduler runs the jobs: an evening job downloads bars and computes targets, with a retry the next morning if none exist. Before the US open the system runs a read-only preflight checklist, then the execute step, with two retries after a transient failure. After the open a reconcile job records fills and commissions and checks the drawdown breaker.

Research discipline

The central problem is multiple testing. Try enough configurations on one history and the best of them will look good by chance. Kestrel counts every walk-forward run and every grid cell in an append-only trial log, and the statistics below read that count. Controls (shuffled labels, within-date score permutations, time shifts) are logged but not counted.

Two statistics carry most of the weight, both from Bailey and López de Prado and co-authors. The deflated Sharpe ratio (DSR) corrects an observed Sharpe ratio (mean excess return divided by its standard deviation) for the number of trials and for non-normal returns, the two sources of inflation named in its abstract (Bailey and López de Prado, 2014). In the form my protocol document uses, with SR-hat the per-period Sharpe ratio of the selected strategy:

PSR(SR*) = Phi( (SR_hat - SR*) * sqrt(T - 1)
                / sqrt(1 - g3*SR_hat + ((g4-1)/4) * SR_hat^2) )
SR0      = sqrt(V) * ( (1-gamma) * Phi^-1(1 - 1/N)
                       + gamma * Phi^-1(1 - 1/(N*e)) )
DSR      = PSR(SR0)

Here T is the number of return observations, g3 and g4 the skewness and raw kurtosis, V the variance of Sharpe ratios across trials, N the number of independent trials, and gamma the Euler-Mascheroni constant. DSR is the probability that the true Sharpe ratio exceeds SR0, the best value expected from N strategies with no skill. I use weekly net returns, because plugging an annualised Sharpe ratio into a daily T breaks the independence assumption. N is the weak input when trials are correlated, so DSR is a filter, not a verdict.

The probability of backtest overfitting (PBO) answers a different question. Bailey, Borwein, López de Prado and Zhu define the selection process as overfitting if the strategy with the best in-sample performance has an expected rank below the median out of sample, and PBO as the probability of that event. They estimate it with combinatorially symmetric cross-validation (CSCV), which they describe as model-free and nonparametric (Bailey et al., revised February 2015). In practice: build a matrix of per-period returns for every registered configuration, cut the rows into an even number of blocks, take every way of choosing half the blocks as in-sample, find the in-sample winner, and record its out-of-sample relative rank. PBO is the share of combinations where that rank is at or below the median. In Kestrel, the grid command over top-k, rebalance cadence and rank buffer computes it.

PBO says whether the selection rule picks winners that persist among the configurations I gave it, not whether the winner has an edge in absolute terms. The table lists what each check is for, and what it cannot do.

CheckGuards againstDoes not guard against
Walk-forward, expanding windowTraining on the future; matches the live retrain cadenceMany trials; it gives one out-of-sample path, so no spread
Purge gap of horizon plus one dayTraining labels that overlap the test windowFeature windows that reach into test prices (the protocol adds an embargo for that)
Newey-West (HAC) t-statistic on the information coefficient (IC)Overlapping labels making the daily IC, the rank correlation of scores with forward returns, look independentWrong sign convention or a leaky feature
Deflated Sharpe ratioSelection bias from many trials; non-normal returnsA badly estimated trial count; a biased universe
PBO via CSCVA selection rule whose in-sample winner fades out of sampleAbsence of any edge; it only compares the configurations supplied
Shuffle and time-shift controlsA pipeline that finds signal in noiseReal but unexploitable signal (costs, capacity)
Locked holdout, one lookTuning on the final testLow power: three years can confirm only a large effect

Two choices came from the controls rather than from the literature. A five-lag HAC t-statistic was too optimistic under shuffled labels, because a model fixed for a year keeps its factor tilt for the whole fold. The IC statistic now uses at least 21 Newey-West lags, or twice the horizon if larger. And the hurdle of t at 3 for the mean IC is borrowed from Harvey, Liu and Zhu, who argue that a newly discovered factor needs a t-ratio greater than 3.0, not 2.0 (NBER w20592). They derived it for factor premia, so applying it to an IC is a convention, and the protocol says so.

The gates are written before results exist: integrity (look-ahead, purge and parity tests), controls, signal, selection (DSR, PBO, minimum backtest length), economics, robustness and a one-look holdout. A strategy that fails a gate is reported as "no edge demonstrated", with the gate named, not as "marginal". A sub-test whose input was never stored is "not evaluated", never guessed, and a gate containing one cannot pass. A pass is a necessary filter, not proof, and live results are the only true out-of-sample.

A checklist for any backtest

The discipline above reduces to eight steps that apply to any strategy research, whatever the tools.

  1. Fix one timing rule and test it. Decide from data up to the close of day t, trade at the open of day t+1, and test that no feature changes when later dates are removed.
  2. Walk forward, with a purge. Leave a gap of the label horizon plus one day, and add an embargo where feature windows reach into test prices.
  3. Log every trial in an append-only file before looking at results; the count feeds the later corrections.
  4. Run controls that should find nothing. Shuffle labels, permute scores within each date, and shift time. Signal there is noise.
  5. Use overlap-robust statistics. Use a Newey-West t-statistic with enough lags, checked against your shuffled controls.
  6. Deflate for selection. Compute the deflated Sharpe ratio and the probability of backtest overfitting from the logged trials, and treat both as filters.
  7. Count costs and the universe. Judge net returns, and state plainly if the universe was chosen with hindsight.
  8. Write the gates first and look at the holdout once. Report a failure as "no edge demonstrated", and a sub-test with missing input as "not evaluated", never a pass.

Why Python for research and Rust for risk

Rust was not chosen for speed. My decision record says so: ingest is bound by the broker's request pacing, the daily engine handles about ten orders, and the research stack already runs on native code (polars, numpy, LightGBM).

What Rust buys is strict types and exhaustive tests for the code that decides what may be sent, as one pure function with no I/O. The costs are two languages joined by file contracts, and a build step that has to stay in sync: the execute command refuses to transmit when the compiled extension does not match the Rust sources. I rejected an all-Rust loop because it would have put the less-used broker client on the riskiest path. The Rust engine binary serves as a differential oracle: tests check that Python gets the same orders from the compiled core as the binary does on the same files. An intraday strategy would reverse the split.

Paper trading, and how it is run

Paper trading runs on the broker's paper account, with the setup above. It is a plumbing test, not a performance test. The first transmitting runs exercised the pre-trade checks, including a cash check that defers orders the account cannot yet pay for.

Each run is a dry run by default. A dry run snapshots positions, open orders of every client, executions and account values, runs the guards, builds the plan, and records the intended orders in the ledger without sending anything. Only an explicit transmit flag or setting sends. Each order carries a reference built from strategy, as-of date and symbol, so a rerun cannot send the same order twice, and every non-zero exit runs an alert command.

Safety and security design

Kestrel's checks protect against its own mistakes, not against other software; the notes are a threat model for one owner on one machine.

  • Kill switch. A file whose presence makes every run refuse to trade, read before each order.
  • Gating real money. A live account needs an explicit opt-in that expires, and a passing verdict or a written reason for unvalidated money.
  • Credentials. Kestrel stores no broker password; it only uses a session that is already authenticated.
  • Read-only LLM access. The MCP server has no acting tool and opens the ledger read-only.

What is still open

  • The verdict fails. Both universes were picked in 2026 with hindsight and carry survivorship bias: the research default is a set of large caps, the paper test a separate, screened set of stocks. A point-in-time universe with delisted stocks is the next data step, and no result built on the current one can pass the robustness gate.
  • The holdout is unused, and all research figures are in-sample. I have recorded no real-money fill.
  • Several sub-tests are not stored, so their gates read "not evaluated": among them the superior-predictive-ability test and the minimum backtest length check.
  • Execution is basic. Orders are market-on-open without a limit price, and fills and commissions are unverified on the paper account.
  • Hosting. The loop runs on a single personal machine, so a missed run is possible.
  • Review. Nobody but me has reviewed the code or the security posture, and a design for a second user is not built.

Sources