<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Rasmus Suonio</title><link>https://rasmuscodes.github.io/</link><description>Company research that states the call, the price and the evidence; the trading bots, simulators and data tools I build; a portfolio shown by weight; and essays.</description><language>en</language><atom:link href="https://rasmuscodes.github.io/feed.xml" rel="self" type="application/rss+xml"/><item><title>Kalman filters for pairs trading: better hedge ratios, no better trades</title><link>https://rasmuscodes.github.io/projects/kalman-pairs/</link><guid isPermaLink="true">https://rasmuscodes.github.io/projects/kalman-pairs/</guid><pubDate>Sun, 29 Nov 2026 12:00:00 +0000</pubDate><description>A statistical-arbitrage laboratory built from the mathematics up - Kalman filter, smoother, likelihood, EM, cointegration and structural-break tests written from scratch - and a pre-registered test of whether dynamic hedge ratios beat static and rolling regression after costs.</description><category>statistical arbitrage</category><category>pairs trading</category><category>kalman filter</category><category>cointegration</category><category>backtesting</category><content:encoded><![CDATA[<p>Pairs trading bets that two related stocks drift back together. Everything rests on the hedge ratio: how many dollars of one stock offset a dollar of the other. A Kalman filter lets that ratio change every day instead of fixing it once, and many guides present this as a better pairs strategy. I wanted to know whether it really is, and to learn the mathematics properly on the way, so I wrote the filter, the smoother, maximum likelihood, EM, the cointegration tests, the structural-break tests and an event-driven backtester myself, and checked each piece against statsmodels and pykalman.</p>
<p>Try it below. The <strong>Kalman lab</strong> filters a synthetic pair with a known hedge ratio live in your browser: move the process and measurement noise and watch the gain, the variances before and after each update, the innovations, the likelihood surface and the trading result change. <strong>Pairs</strong> shows 24 named pairs, among them LITE/MRVL, NVDA/QQQ and CAT/DE, with their hedge ratios, z-scores, break monitors and a check of whether a deviation is actually tradable after costs. <strong>Study</strong> holds the full results.</p>
<div class="kpt-wrap"><iframe id="kpt-demo" src="https://rasmuscodes.github.io/apps/kalman-pairs/index.html?embed=1&v=20261129e" title="Kalman pairs terminal: live Kalman lab, named pairs and study results"></iframe></div>
<script>
(function () {
  var frame = document.getElementById("kpt-demo");
  if (!frame) return;
  window.addEventListener("message", function (ev) {
    if (ev.origin !== window.location.origin || ev.source !== frame.contentWindow) return;
    var d = ev.data || {};
    if (d.type === "kpt:height" && d.height > 300) frame.style.height = Math.ceil(d.height) + "px";
  });
})();
</script>
<style>
.kpt-wrap { width: min(1240px, calc(100vw - 32px)); position: relative; left: 50%; transform: translateX(-50%); margin: 28px 0 36px; border: 1px solid var(--rule); border-radius: 12px; overflow: hidden; background: var(--bg); }
.kpt-wrap iframe { display: block; width: 100%; height: 1800px; border: 0; background: transparent; }
@media (max-width: 640px) { .kpt-wrap { width: calc(100vw - 24px); } }
</style>
<h2 id="what-i-found">What I found <a class="header-anchor" href="#what-i-found">#</a></h2>
<p>I wrote the test down before running it: S&amp;P 500 members in semiconductor, technology and industrial industries, using CRSP data so that companies later acquired or delisted are still in the sample. Each strategy was fitted on two years and traded for the next six months, rolling forward. One configuration per method was chosen on 2005-2012 and run once on 2013-2024. Trades fill at the next day’s open and pay quoted spreads, market impact, commission and short-borrow fees.</p>
<ul>
<li><strong>No method beat rolling regression.</strong> The Kalman hedge earned a net Sharpe ratio of -0.28 against +0.08 for a 250-day rolling regression and -0.25 for a static one. A Kalman model that treats the spread itself as a hidden mean-reverting state earned +0.01. None of the three registered comparisons favours a Kalman variant: the best p-value after the Holm multiple-testing correction is 0.55. The configuration that won validation, at a Sharpe of 0.65, scored -0.28 on the test.</li>
<li><strong>Kalman filters do hedge better.</strong> A moderately adaptive Kalman hedge cut the variance of next-day hedged returns by about 8% against the rolling regression in 80% of 480 test pair-windows. On synthetic pairs with a drifting hedge ratio it tracked the truth with a seventh of the rolling regression’s error. Rolling windows estimate the slope from too little movement in the hedge stock. Better hedges simply did not make better trades.</li>
<li><strong>The noise setting decides everything, and maximum likelihood picks the worst one.</strong> On the test years the Kalman strategy’s Sharpe ranged from -0.31 to +0.75 across noise settings. Maximum likelihood chose noise that lets the hedge ratio jump around (a median ratio of 56 to the measurement noise). That fits the data best because the filter absorbs every deviation as it happens, which leaves nothing to trade: 2,065 trades and a net Sharpe of -1.05.</li>
<li><strong>An adaptive filter follows a broken relationship.</strong> On synthetic pairs whose cointegration dies, a CUSUM monitor on the maximum-likelihood filter’s surprises caught the breakdown within six months only 18% of the time, against 58% for the same monitor on a relationship frozen at formation, at the same false-alarm rate. The textbook CUSUM test rejected stability on 96% of perfectly stable pairs, because a persistent spread breaks its assumptions.</li>
<li><strong>Costs and timing.</strong> Before costs the rolling regression had a test Sharpe of 0.33; costs of 66-78 basis points a year took most of it. Filling at the signal’s own closing price instead of the next open would have added up to 0.2 of Sharpe that a trader could never capture.</li>
</ul>
<p>Two gold ETFs holding the same metal and two S&amp;P 500 ETFs are cointegrated by construction, yet every method lost money on them: the spread is too small to pay for trading. Marvell’s agreement to buy Lumentum on 1 November 2026 breaks the LITE/MRVL relationship in a way the break monitor cannot see, because the two stocks suddenly move more closely together, not less.</p>
<h2 id="how-it-works">How it works <a class="header-anchor" href="#how-it-works">#</a></h2>
<ul>
<li><strong>The mathematics, from scratch.</strong> A general linear Gaussian state-space model with time-varying matrices, the Kalman filter in Joseph form with missing data and an exact likelihood, the Rauch-Tung-Striebel smoother, maximum likelihood with parameter transforms and standard errors, EM, steady-state analysis linking the filter to exponential smoothing and rolling windows, and multivariate common-trend models. The filter matches statsmodels to 5e-7 in log-likelihood and pykalman’s EM exactly. Each derivation is written out in the repository.</li>
<li><strong>Statistics.</strong> Augmented Dickey-Fuller and Engle-Granger tests with MacKinnon p-values (identical to statsmodels), Ornstein-Uhlenbeck half-lives and a closed-form probability that a trade converges before its stop, CUSUM, Page’s CUSUM, Andrews’ sup-F and PELT change-point detection.</li>
<li><strong>Backtester.</strong> Event-driven, with signal timestamps, execution delays, quote-based spreads, square-root market impact, commissions, daily borrow, exposure limits, stops and delistings. Tests check that every dollar of cash flow is accounted for and that future prices never change a past signal.</li>
<li><strong>Terminal.</strong> The browser runs a JavaScript port of the filter that reproduces the Python results to nine decimal places. The study views show only derived results, never the licensed or vendor prices.</li>
</ul>
<h2 id="limits">Limits <a class="header-anchor" href="#limits">#</a></h2>
<ul>
<li>Daily data only, and short-borrow fees and availability are assumptions.</li>
<li>The test can only detect Sharpe differences larger than about 0.3. The observed difference had the wrong sign anyway.</li>
<li>The 24 named pairs are hand-picked stocks that exist today, so they illustrate the methods; the CRSP study is the evidence.</li>
<li>No live trading results exist.</li>
</ul>
]]></content:encoded></item><item><title>A merger-arbitrage lab</title><link>https://rasmuscodes.github.io/projects/merger-arb/</link><guid isPermaLink="true">https://rasmuscodes.github.io/projects/merger-arb/</guid><pubDate>Wed, 25 Nov 2026 12:00:00 +0000</pubDate><description>Is the 21.5% spread on Marvell’s all-stock bid for Lumentum a mispricing or fair pay for the risk? Verified deal terms, a break-price model, scenarios through a margin account, and a manually approved execution tool.</description><category>merger arbitrage</category><category>event-driven</category><category>semiconductors</category><category>risk management</category><content:encoded><![CDATA[<p>On 2 November 2026 Marvell agreed to buy Lumentum for a fixed 4.5 Marvell shares per Lumentum share, with closing guided for the first half of 2028. Three weeks later Lumentum trades 21.5% below the value of those shares. Merger arbitrage buys Lumentum and shorts 4.5 Marvell shares per share, collecting the gap if the deal closes. A spread that wide on a signed deal between two large companies looks like an opportunity, so the first job was to check it is not a data error and then to work out what it pays for.</p>
<p><strong>It is not a data error.</strong> The 4.50 ratio comes from the merger agreement itself. The closing prices match an independent Cboe download exactly and agree with Google Finance. The stale after-hours quotes some sources show are flagged and ignored.</p>
<p><strong>It is wide for reasons.</strong> Closing takes about 16 months. China’s merger regulator is the main approval risk, and it has let US chip deals lapse before. Both sets of shareholders are unhappy, and Lumentum’s vote needs a majority of all outstanding shares. The whole AI-semiconductor complex has just fallen 25-50%. Borrowing Marvell is cheap and plentiful, so the short leg does not explain the spread.</p>
<p><strong>Antitrust is the crux, and China is the weak link.</strong> The combined company would be the dominant merchant supplier of the DSP chips inside optical modules (a Chinese module maker’s prospectus puts Broadcom and Marvell at about 90% of that market). It would also be a laser and module rival of the Chinese firms that buy those chips. That is the profile China’s regulator approved only with conditions after 13-18 months in Nvidia-Mellanox and AMD-Xilinx. It let four US deals time out when tensions were high. Gate by gate (US 93%, both shareholder votes 81%, EU 94%, China 69%), completion comes to about 48%, essentially the market’s own estimate.</p>
<p><strong>How antitrust worries move the stocks.</strong> Marvell fell about 21% on the deal, so bad regulatory news lifts Marvell more than it sinks Lumentum. If three quarters of that discount would reverse on a break, a US lawsuit moves Marvell about +12% and Lumentum slightly <em>up</em> too. The hedged position loses about $21 per Lumentum share for every 10-point drop in the market’s completion odds, whichever leg moves. Past deals behaved the same way: surprise blocks blew spreads out by 12-130 points while the acquirers rallied, and approvals tightened them by about 8 points.</p>
<p><strong>Verdict: potentially attractive, small size only.</strong> If the deal closes, the trade earns about $101 per Lumentum share. If it breaks, the result depends on where Lumentum would trade on its own and how much of Marvell’s drop reverses. A triple check changed the call from “no trade” for two reasons. The model had left out the $3.2bn fee Marvell owes Lumentum if regulators kill the deal. And its base case for Lumentum’s break value used the factor model’s estimate as the <em>best</em> case: $613, which matches how 49 chip stocks moved against the same model in this crash, ±15%. Corrected, the trade earns about 5% a year above Treasuries at 48% odds, just over a 5% hurdle. The catch is that the market prices Lumentum’s break value at only $494-534; if the market is right, the trade is roughly fair, and under the stress case it loses. So the dashboard reads WATCH, and a $10k account should hold at most one 2-for-9 lot.</p>
<p>The dashboard below recomputes everything in your browser from the sliders: the spread, completion and break payoffs, break-even probability, what each regulatory headline does, scenarios simulated day by day through an IBKR-style margin account, survival-first position sizing and a Monte Carlo. It has no trading functionality. The repository also contains a local-only execution tool for Interactive Brokers: paper by default, typed approval, short leg first, partial-fill and unhedged-leg alerts, an alert-only spread-trigger ladder and a no-orders readiness check. The triple check found and fixed serious safety bugs in that tool (for example, “cancel all” could re-send an order); it still needs a paper-account test against real IBKR software.</p>
<iframe src="https://rasmuscodes.github.io/apps/merger-arb/?v=5" title="Merger arbitrage lab dashboard" loading="lazy" style="width:100%;height:3100px;border:0;border-radius:10px"></iframe>
<h2 id="how-it-was-built">How it was built <a class="header-anchor" href="#how-it-was-built">#</a></h2>
<ul>
<li><strong>Deal terms</strong> come from the merger agreement: the ratio, the absence of a collar, the outside-date chain to 1 August 2028, a $3.2bn regulatory reverse fee, the vote standards, the efforts covenant and dividend policy. A new deal is a new data file.</li>
<li><strong>Break prices</strong> project both stocks forward from their unaffected 28 October prices with factor models estimated before any deal news. Resetting to the unaffected prices would be wrong after a sector crash: Lumentum would “nearly double” on a break, and so would Marvell.</li>
<li><strong>Comparables:</strong> 21 large US deals from CRSP, with terms validated by checking that each completed deal’s spread converged to zero. Only Anthem/Cigna, later blocked in court, traded wider at the same stage.</li>
<li><strong>Risk:</strong> IBKR’s published margin, interest and borrow rules. At full Reg T leverage, a Marvell rally while Lumentum lags triggers a margin call even in a scenario where the deal later closes.</li>
</ul>
<p>Market data from the close of 24 November 2026. Research only, not investment advice.</p>
]]></content:encoded></item><item><title>A cross-asset volatility desk on thirty years of option data</title><link>https://rasmuscodes.github.io/projects/volatility-desk/</link><guid isPermaLink="true">https://rasmuscodes.github.io/projects/volatility-desk/</guid><pubDate>Wed, 25 Nov 2026 12:00:00 +0000</pubDate><description>Five surface models compared on 371 dates, seventeen option strategies backtested day by day, walk-forward forecasts and dispersion trades, with a working volatility terminal below.</description><category>options</category><category>volatility</category><category>derivatives pricing</category><category>forecasting</category><category>backtesting</category><content:encoded><![CDATA[<p>A research platform for equity-index volatility, built on OptionMetrics and Cboe option data through WRDS: every S&amp;P 500 option quote from 1996 to November 2026, chains for SPY, QQQ and IWM, standardized surfaces for the fifty largest index members, and VIX futures. It fits volatility surfaces, backtests option structures with Greek P&amp;L attribution, forecasts volatility and correlation out of sample, and tests whether the forecasts make money after costs.</p>
<p>The terminal below runs entirely in your browser. Pick an underlying and a date (calm days and crisis days from 2000 to 2026), turn the implied-volatility surface in 3D and compare the five models, build an option strategy, then move spot, volatility and time and see where the P&amp;L comes from. The Scenarios tab replays fifteen historical stress episodes on your position; Backtests shows thirty years of results for seventeen strategies.</p>
<div id="voldesk-app"></div>
<link rel="stylesheet" href="https://rasmuscodes.github.io/apps/volatility-desk/app/voldesk.css?v=20261125a">
<script type="module" src="https://rasmuscodes.github.io/apps/volatility-desk/app/voldesk.js?v=20261125a"></script>
<h2 id="what-i-found">What I found <a class="header-anchor" href="#what-i-found">#</a></h2>
<p><strong>The closest fit is not the safest surface.</strong> On 371 S&amp;P 500 month-ends, SVI misses the market by a median 0.24 volatility points and puts 89% of quotes inside the bid-ask, but its extrapolated wings carry calendar arbitrage. Extended SSVI is free of static arbitrage on every date at twice the error; Heston fits worst at 0.97 points.</p>
<div class="table-wrap"><table>
<thead>
<tr>
<th>Model</th>
<th style="text-align:right">Median error, vol points</th>
<th style="text-align:right">Quotes inside the bid-ask</th>
<th>Static arbitrage</th>
</tr>
</thead>
<tbody>
<tr>
<td>SVI</td>
<td style="text-align:right">0.24</td>
<td style="text-align:right">89%</td>
<td>In 8% of extrapolated grid points</td>
</tr>
<tr>
<td>SABR</td>
<td style="text-align:right">0.37</td>
<td style="text-align:right">70%</td>
<td>In 3% of extrapolated grid points</td>
</tr>
<tr>
<td>Extended SSVI</td>
<td style="text-align:right">0.52</td>
<td style="text-align:right">63%</td>
<td>None, by construction</td>
</tr>
<tr>
<td>SSVI</td>
<td style="text-align:right">0.78</td>
<td style="text-align:right">41%</td>
<td>None, by construction</td>
</tr>
<tr>
<td>Heston</td>
<td style="text-align:right">0.97</td>
<td style="text-align:right">26%</td>
<td>None (a consistent model)</td>
</tr>
</tbody>
</table></div>
<p><strong>Selling index volatility paid before costs; costs decide most of the rest.</strong> A short at-the-money straddle rolled monthly earned 5.3% of notional a year before costs and 4.0% after, paid for with crash losses (−10.5% of notional on the worst day). Delta-hedged every day, the same straddle earned 3.5% a year before costs, 1.8% after realistic costs, and nothing after stressed costs. Calendars, diagonals, butterflies and risk reversals made almost nothing before costs and lost money after. The delta-hedged short 25-delta put and call had the best risk-adjusted results.</p>
<p><strong>Forecasts are good; timing with them is not.</strong> A log-HAR model with the VIX forecasts S&amp;P 500 realized variance 7.5% and 26% better than an exponentially weighted average at one and five days, and implied plus realized correlation predicts next month’s correlation best (out-of-sample R² 36.5%). But no forecast-driven rule for timing the variance premium beat a constant allocation after costs; volatility targeting cut the index’s drawdown from −84% to −65% and nudged its Sharpe ratio up.</p>
<p><strong>There is a correlation premium.</strong> Implied correlation between the fifty largest S&amp;P 500 members exceeded next month’s realized correlation by 0.04 on average (t = 5.1), with severe losses when correlations spike.</p>
<h2 id="data-and-its-limits">Data and its limits <a class="header-anchor" href="#data-and-its-limits">#</a></h2>
<p>Option data are licensed (OptionMetrics, Cboe, Datastream and CRSP through WRDS) and are never published: the terminal ships fitted model parameters, aggregate statistics and backtest results only, so it draws the models’ surfaces and the quoted range rather than the quotes themselves. The two vendors’ quotes differ on stressed days; the history switches from OptionMetrics to Cboe in September 2025. Single stocks have standardized surfaces but no chains here, so dispersion trades are variance-based. Backtests are historical simulations with estimated costs, not evidence of a tradable edge.</p>
<h2 id="how-its-built">How it’s built <a class="header-anchor" href="#how-its-built">#</a></h2>
<p>A Python package (pricing, data, surfaces, strategies, backtest, forecasting, dispersion) with 35 tests that run in CI on synthetic option chains, five research reports, and a vanilla-JavaScript terminal that reprices everything in the browser, including Heston by the COS method, and checks itself against values computed in Python.</p>
]]></content:encoded></item><item><title>Government bond relative value across six markets</title><link>https://rasmuscodes.github.io/projects/fixed-income/</link><guid isPermaLink="true">https://rasmuscodes.github.io/projects/fixed-income/</guid><pubDate>Tue, 24 Nov 2026 12:00:00 +0000</pubDate><description>A research engine and live terminal for US, German, French, UK, Japanese and Polish yield curves - curve fitting, DV01-neutral trades, carry, roll-down and scenarios - with backtests that report what did not work.</description><category>fixed income</category><category>yield curves</category><category>relative value</category><category>rates</category><category>backtesting</category><content:encoded><![CDATA[<p>Relative-value traders in government bonds look for points on a curve, or spreads between curves, that are cheap or rich once risk is accounted for. I built the tools for that - curve models, risk, trade construction, a scanner and a backtester - for six markets, and tested which of the classic signals would have made money after costs and out of sample.</p>
<p>The terminal below runs the same engine in your browser. Pick a market and a week, fit the curve with five models, compare it with any earlier week, then build a steepener, flattener, butterfly or cross-country spread at a target DV01 and see its carry, roll-down, key-rate risk and profit or loss under hypothetical, statistical and historical shocks. Every number is computed live from weekly official data; nothing is a static illustration.</p>
<link rel="stylesheet" href="https://rasmuscodes.github.io/apps/fixed-income/terminal.css?v=20261124a">
<div id="fi-terminal" class="fi-terminal" data-base="/apps/fixed-income/"><p class="fi-loading">Loading the terminal...</p></div>
<script src="https://rasmuscodes.github.io/apps/fixed-income/firv.js?v=20261124a"></script>
<script src="https://rasmuscodes.github.io/apps/fixed-income/terminal.js?v=20261124a"></script>
<h2 id="what-i-found">What I found <a class="header-anchor" href="#what-i-found">#</a></h2>
<div class="table-wrap"><table>
<thead>
<tr>
<th>Question</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr>
<td>Which curve model fits best?</td>
<td>Out of sample (each maturity left out and predicted), Nelson-Siegel-Svensson: 6.3 bp in the US, 3.3 bp in France, 4.5 bp for Polish bonds. In Japan, where every maturity from 1 to 10 years is published, a cubic spline is best (2.6 bp). Nelson-Siegel is worst in the US, France and Japan. The smoothing spline adds the least day-to-day noise at unobserved maturities in all 12 market-regime windows tested.</td>
</tr>
<tr>
<td>What moves curves?</td>
<td>Level explains 80-90% of daily changes since 2000, slope 8-13%, curvature 1-3%. Level and slope keep the same shape across two-year windows; curvature does not, so a curvature trade estimated in one period can carry level or slope risk in the next.</td>
</tr>
<tr>
<td>Does fading curve and butterfly dislocations pay?</td>
<td>No. Fading extreme 2s10s slopes lost money out of sample in all six markets (walk-forward Sharpe ratios from -0.28 to -0.52). Butterflies and cross-country 10-year spreads were flat to negative after costs, weighting butterflies by principal components did not help, and Polish trades did not cover the bid/offer measured in the official fixing.</td>
</tr>
<tr>
<td>Did anything survive?</td>
<td>One of 36 walk-forward tests clears a multiple-testing bar: mean reversion of the US 10-year swap spread, 27 bp per unit of DV01 a year, Sharpe 0.50, t-statistic 3.8 (2004-2016, on discontinued LIBOR swap rates). Ten of the twelve results with a t-statistic beyond 2 are reliable losses.</td>
</tr>
</tbody>
</table></div>
<h2 id="france-versus-poland">France versus Poland <a class="header-anchor" href="#france-versus-poland">#</a></h2>
<p>The case study compares two borrowers in different currencies under different central banks: France with much higher debt (about 120% of GDP against 77% in 2026, OECD estimates), Poland with the larger deficit (6.9% against 5.0% of GDP) and the faster-rising debt ratio. On 20 November 2026 the Polish 10-year yield was 136 bp above the French one, close to its five-year low of 130 bp. Hedged into euros at the short-rate differential, the Polish bond yielded only 5 bp more. Weekly Polish and French 10-year changes moved with a beta of 0.96 and a correlation of 0.65. None of the candidate trades - 2-, 5- and 10-year spreads and a curve box - earned a reliable return historically, and for the static versions the assumed cost of rolling Polish bonds decided the sign. The study lays out the evidence and what would have to be true for either side; it makes no call.</p>
<h2 id="data">Data <a class="header-anchor" href="#data">#</a></h2>
<p>Every yield comes from an official publisher, and each is labelled in the terminal: the U.S. Treasury par curve, the Bundesbank and Bank of England fitted curves, the Banque de France constant-maturity OAT yields, Japan’s Ministry of Finance yields, and the BondSpot fixing of Polish government bonds, to which I fit a curve every week. Macro inputs come from the BIS, OECD, ECB and New York Fed. Conventions were checked in the data rather than assumed: the Bundesbank, Fed and ECB yields reproduce from their published parameters only with continuous compounding, and while Bank Rate sat at 5.25% the Bank of England’s one-month OIS rate averaged 5.19%, which fits continuous compounding of an overnight rate a few basis points below Bank Rate (an annual convention would read about 5.33%). Raw Polish fixings and vendor series (ICE swap rates, Moody’s yields) are not redistributed.</p>
<h2 id="how-it-is-built">How it is built <a class="header-anchor" href="#how-it-is-built">#</a></h2>
<p>A Python package (<code>firv</code>) with curve models (Nelson-Siegel, Svensson, smoothing and cubic splines, bootstrapping), bond and swap analytics, key-rate risk, carry and roll-down, scenario revaluation, trade constructors with DV01, beta, regression and principal-component hedges, a relative-value scanner and a walk-forward backtester with transaction and roll costs. Trades are sized by yield DV01, as traders quote them; risk is aggregated on the zero curve. The terminal is a JavaScript port of the engine that matches the Python on all 53 reference values, and 36 Python tests cover the analytics and the data.</p>
<h2 id="limits">Limits <a class="header-anchor" href="#limits">#</a></h2>
<ul>
<li>Backtests use constant-maturity yields, not individual bonds: repo specials, on-the-run premia and auction cycles are ignored, and transaction costs outside Poland are assumptions (shown at zero, one and two times).</li>
<li>No free Treasury futures prices could be used, so the futures-basis module (conversion factors, net basis, implied repo) is analytics only.</li>
<li>The Polish curve stops at about 10 years in recent years, because the fixing has had no longer fixed-rate bonds; the 10-year point is extrapolated by up to a year.</li>
<li>Swap data are LIBOR swaps that end in 2016; UK swap spreads use the Bank of England’s SONIA OIS curve.</li>
</ul>
]]></content:encoded></item><item><title>A portfolio manager that explains itself, and what optimization is worth</title><link>https://rasmuscodes.github.io/projects/portfolio-manager/</link><guid isPermaLink="true">https://rasmuscodes.github.io/projects/portfolio-manager/</guid><pubDate>Mon, 23 Nov 2026 12:00:00 +0000</pubDate><description>A portfolio construction and risk engine that turns research signals into positions, explains every weight, stress-tests and backtests the result, with a pre-registered test of fourteen methods on 55 years of public data and a live demo that runs the engine in your browser.</description><category>portfolio construction</category><category>risk management</category><category>optimization</category><category>signal combination</category><content:encoded><![CDATA[<p>A portfolio manager has to turn many imperfect signals into one set of positions without letting any one input, or the optimizer itself, take over. I built the engine that does that: it reads signals from independent research systems through one point-in-time interface, builds portfolios with fourteen construction methods under realistic constraints, explains why each position is the size it is, measures the risk, stress-tests it and backtests it walk-forward with trading costs. Then I asked the question every optimizer has to answer: does it beat simply holding everything in equal weights?</p>
<p>The demo below runs the same engine in your browser on monthly data for 12 US industries and two Treasury maturities since 1962, or on nine factor “strategy sleeves”. Pick a method, change the inputs or the constraints, and read the explanation under the weights.</p>
<div class="qpm-wrap"><iframe id="qpm-demo" src="https://rasmuscodes.github.io/apps/portfolio-manager/" title="Portfolio manager demo: build, explain, stress and backtest portfolios in the browser" loading="lazy"></iframe></div>
<script>
(function () {
  var frame = document.getElementById("qpm-demo");
  if (!frame) return;
  window.addEventListener("message", function (ev) {
    if (ev.origin !== window.location.origin || ev.source !== frame.contentWindow) return;
    var d = ev.data || {};
    if (d.type === "qpm-demo-height" && d.height > 400) frame.style.height = Math.ceil(d.height) + "px";
  });
})();
</script>
<style>
.qpm-wrap { width: min(1240px, calc(100vw - 48px)); position: relative; left: 50%; transform: translateX(-50%); margin: 28px 0 36px; border: 1px solid var(--rule); border-radius: 12px; overflow: hidden; background: var(--bg); }
.qpm-wrap iframe { display: block; width: 100%; height: 1900px; border: 0; background: transparent; }
@media (max-width: 640px) { .qpm-wrap { width: calc(100vw - 24px); } }
</style>
<h2 id="what-the-demo-does">What the demo does <a class="header-anchor" href="#what-the-demo-does">#</a></h2>
<ul>
<li><strong>Construct.</strong> Thirteen methods, from equal weights to mean-variance, maximum Sharpe, risk parity, equal risk contribution, hierarchical risk parity, Black-Litterman, Kelly and a market-neutral book, under position, sector, gross-exposure and volatility limits. You can edit any asset’s expected return or volatility, or add an asset of your own.</li>
<li><strong>Why each position.</strong> For optimizer-based methods every weight is decomposed exactly: the asset’s expected return, what the binding constraints cost (their shadow prices act like changes to expected returns), the part of the return the other assets already deliver, and the risk they cannot hedge away.</li>
<li><strong>Signals.</strong> Research signals arrive with their family, horizon, provenance, model version and a track record measured month by month. You can switch them on and off, combine them five ways, add your own, and use the result as expected returns.</li>
<li><strong>Risk and stress tests.</strong> Value at risk five ways, factor exposures, backfilled drawdowns, liquidity at different fund sizes, correlations in calm and turbulent markets, and nine scenarios (2008, 2020, 2022, the 1987 crash, the dot-com bust, an AI-capex reversal, a volatility spike, a bond sell-off, a credit crisis) that you can edit or extend.</li>
<li><strong>Estimation error lab.</strong> It treats the current inputs as the truth, simulates histories from them, re-estimates and re-optimizes, and shows how much less the portfolios deliver than they promise.</li>
<li><strong>Backtests.</strong> Walk-forward backtests with costs since 1972, recomputed in the browser, next to the pre-registered results.</li>
</ul>
<h2 id="what-i-found">What I found <a class="header-anchor" href="#what-i-found">#</a></h2>
<p>I fixed the hypotheses, methods and tests in writing before running anything. The main test pits thirteen methods against equal weights on the industries-and-Treasuries universe from 1972 to 2026, rebalancing monthly with a ten-year estimation window and trading costs of 10 basis points (2 for Treasuries).</p>
<div class="table-wrap"><table>
<thead>
<tr>
<th>Question</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr>
<td>Does any optimizer beat equal weights?</td>
<td>No. The best (Black-Litterman with momentum views) leads by 0.06 of Sharpe, interval −0.03 to +0.15; maximum Sharpe on historical means trails by 0.13. Nothing is significant after correcting for thirteen tests</td>
</tr>
<tr>
<td>Do risk-based methods help?</td>
<td>They deliver the same Sharpe with far less risk: minimum variance runs at 7.7% volatility with an 18% worst drawdown, against 13.1% and 43%</td>
</tr>
<tr>
<td>Where does optimization go wrong?</td>
<td>In the expected returns. With known parameters, errors in the means cost 0.066 of Sharpe and errors in the covariance 0.011; optimizers promised a Sharpe of 0.79 and delivered 0.51</td>
</tr>
<tr>
<td>Does learning how to weight signals beat equal weights?</td>
<td>Yes, against my pre-registered expectation, but only because one signal (industry-level short-term reversal) had a reliably wrong sign. Fixing that sign by hand made equal weights as good as learning</td>
</tr>
<tr>
<td>Does Kelly sizing pay?</td>
<td>It grew wealth fastest and fell 78-86% from peak</td>
</tr>
</tbody>
</table></div>
<figure class="figure"><img loading="lazy" decoding="async" src="https://rasmuscodes.github.io/media/portfolio-manager/estimation-error.png" alt="Promised and delivered Sharpe ratios under estimation error" /><figcaption>Promised and delivered Sharpe ratios under estimation error</figcaption></figure>
<p><strong>Optimization did not create alpha.</strong> Where a method did better, the improvement came from better inputs, such as Black-Litterman’s anchoring to market weights or a correctly signed signal, or from simply taking less risk. Shrinking the inputs and capping positions made optimizers less harmful rather than better. Risk models had their own lessons: on daily data every unconditional value-at-risk model breached too often or in clusters, and stock-bond correlations, which turned negative in the 2000s and 2010s, are positive again in the 2020s.</p>
<h2 id="how-it-works">How it works <a class="header-anchor" href="#how-it-works">#</a></h2>
<ul>
<li><strong>A solver I can explain.</strong> Portfolios come from a quadratic-program solver I wrote (the ADMM algorithm behind OSQP, with an exact final step). It matches the Clarabel interior-point solver to eight decimal places, and the browser runs a line-by-line port of it, checked against the Python version on 54 test cases.</li>
<li><strong>Point-in-time signals.</strong> Every research system hands over the same record. The engine only ever reads signals known at the decision date, and tests rewrite the future to prove that no past decision changes.</li>
<li><strong>Realistic backtests.</strong> Trades are charged spread, commissions and square-root market impact, cash earns the T-bill rate and shorts pay a borrow fee. Execution goes through a two-message interface, and the same orders can be routed through <a href="https://rasmuscodes.github.io/projects/smart-router/">my smart order router</a>, a separate project, for a simulated multi-venue execution.</li>
<li><strong>Statistics.</strong> Paired bootstrap and Jobson-Korkie tests on Sharpe differences, Holm corrections across methods, and a synthetic laboratory where the true signal quality is known.</li>
</ul>
<h2 id="limits">Limits <a class="header-anchor" href="#limits">#</a></h2>
<ul>
<li>Industry portfolios are not instruments; sector funds and futures only cover recent decades, so the cost assumptions are assumptions.</li>
<li>One fourteen-asset universe carries the main result; with hundreds of assets or genuinely strong signals the trade-off between estimation error and opportunity changes.</li>
<li>The built-in signals are simple public ones. The engine is designed to take signals from my other research systems, but those use licensed or private data and are not part of the public study.</li>
<li>Sharpe differences of a few hundredths cannot be detected even in 55 years of monthly data, so several results are absences of evidence rather than proof of equality.</li>
</ul>
<h2 id="how-its-built">How it’s built <a class="header-anchor" href="#how-its-built">#</a></h2>
<p>A Python package (NumPy, pandas, SciPy) with 109 tests, a script that rebuilds every experiment from public data (Ken French’s industry and factor returns and Federal Reserve Treasury yields), and a static browser demo in plain JavaScript with its own SVG charts and no external requests. Data: Kenneth R. French Data Library and FRED.</p>
]]></content:encoded></item><item><title>A poker research lab, from exact equity to exploiting an opponent model</title><link>https://rasmuscodes.github.io/projects/poker-ecosystem/</link><guid isPermaLink="true">https://rasmuscodes.github.io/projects/poker-ecosystem/</guid><pubDate>Mon, 23 Nov 2026 12:00:00 +0000</pubDate><description>Solvers that measure their own error, a Bayesian model of how opponents play, the strategy that exploits it, hand-history analysis, and an interactive lab that runs in the browser.</description><category>poker</category><category>game theory</category><category>rust</category><category>bayesian statistics</category><content:encoded><![CDATA[<p>Most poker tools answer one question: what is the equilibrium play? This project asks the next one as well. How far is a given answer from equilibrium, and what should change when you know how an opponent actually plays? It brings together exact hand evaluation and equity, a family of game-theory solvers that report their own error, a Bayesian model of opponents, exploitative strategies built on that model, and hand-history analysis, in one codebase with one test suite.</p>
<h2 id="try-it">Try it <a class="header-anchor" href="#try-it">#</a></h2>
<p>The lab below is the real engine running in your browser. Pick a spot and press <em>Solve</em>: the convergence chart shows how far the strategy is from equilibrium after each batch of iterations, and the grid shows what every hand does. Then describe how an opponent plays (say, the button folds 70% of the time to river bets), press <em>Compare GTO and exploit</em>, and watch the strategy change and what that change costs in safety. The default spot and opponent are the ones behind the exploitation results below, so the lab reproduces those numbers. In the <em>Hand histories</em> tab, pick a hand to see each player’s range street by street and a review of the river decisions against an equilibrium. <a href="https://rasmuscodes.github.io/apps/poker-ecosystem/">Open it full screen</a> for more room.</p>
<iframe src="https://rasmuscodes.github.io/apps/poker-ecosystem/?embed#solver" title="Poker research lab" loading="lazy" style="width:100%;height:1250px;border:1px solid var(--rule);border-radius:12px;background:var(--bg)"></iframe>
<h2 id="what-it-does">What it does <a class="header-anchor" href="#what-it-does">#</a></h2>
<ul>
<li><strong>Exact evaluation and equity.</strong> Hold’em, Short Deck (both rule sets), Omaha, Five-Card Omaha and Omaha Hi-Lo. Equity by full enumeration for any number of players, on one or two boards, or by Monte Carlo with standard errors. Running it twice is computed exactly: it never changes equity, but it cuts the variance by more than half, because the second run is dealt from what the first left.</li>
<li><strong>The CFR family.</strong> CFR (counterfactual regret minimisation: the strategy plays against itself and shifts towards the moves it regrets not making), CFR+, Linear, Discounted and Predictive CFR, and two Monte Carlo versions, compared on games with known answers.</li>
<li><strong>Range-against-range solving</strong> on the river and turn for Hold’em, Omaha and Short Deck, with exact card removal (who can hold which cards given what everyone else holds), double boards, rake and the 7-2 game’s bounty. It also solves three- and four-way rivers.</li>
<li><strong>Opponent modelling.</strong> Statistics such as how often a player folds to a river bet, estimated with a hierarchical Bayesian model: small samples lean on the player population and every estimate comes with a 90% credible interval. Players are then clustered into types.</li>
<li><strong>Exploitation.</strong> A best response to the model (the most it can win) and restricted Nash responses, which trust the model only partly and so trade some of the gain for safety against being wrong.</li>
<li><strong>Hand histories.</strong> A PokerStars parser that rebuilds every pot, including side pots, rake and straddles (a Mississippi straddle from the button acts last before the flop), works out all-in equity and the luck in each hand, and feeds a searchable database.</li>
<li><strong>Ranges, street by street.</strong> Every action is evidence about the cards behind it. Bayes’ rule with a model of play, built from each player’s own frequencies, turns a hand’s actions into a range for every player at every street.</li>
<li><strong>River review.</strong> Each heads-up river decision is replayed against an equilibrium of that river, solved with the reconstructed ranges and the bet sizes actually used: what the equilibrium does with that hand, what each action is worth, and what the action taken cost.</li>
</ul>
<h2 id="what-is-exact-and-what-is-not">What is exact, and what is not <a class="header-anchor" href="#what-is-exact-and-what-is-not">#</a></h2>
<p>Every result says what it is. Hand values and enumerated equities are exact. A heads-up solve is an approximate equilibrium of the game with the listed bet sizes, and how far it is from equilibrium in that game is computed exactly, as a share of the pot. With three or more players, CFR has no guarantee of reaching an equilibrium at all; those results report NashConv (the total that all players could gain by switching to their best responses) and are labelled as approximations. The opponent model and the street-by-street ranges are checked against simulated players, whose true habits and cards are known; real players’ are not. A river review’s costs are measured against an opponent who plays the equilibrium of that river, not against the real opponent.</p>
<h2 id="what-i-measured">What I measured <a class="header-anchor" href="#what-i-measured">#</a></h2>
<ul>
<li><strong>Known answers.</strong> Kuhn poker’s value comes out at −1/18 to within 5 × 10⁻¹², Leduc hold’em’s at −0.0856, and a river with a closed-form solution (the nuts or air against bluff-catchers) matches the theory’s bluffing and calling frequencies to four decimal places.</li>
<li><strong>Algorithms.</strong> On Leduc, after 1,000 iterations, plain CFR is 0.012 chips a hand from equilibrium and Discounted CFR 0.0002. On real river spots Discounted CFR reaches 0.1% of the pot in about 150 iterations, including an Omaha river with 32,352 against 41,844 four-card hands.</li>
<li><strong>Abstraction.</strong> Grouping river hands into strength buckets costs 16% of the pot with 2 buckets and 0.16% with 40, against 0.003% for the exact solve.</li>
<li><strong>More players.</strong> Exact three- and four-way rivers cost about twelve times more per added player. NashConv still fell to about 0.03% of the pot, an observation rather than a guarantee.</li>
<li><strong>Exploitation.</strong> Against a button that folds 70% of the time to river bets, a restricted Nash response wins 37% of the pot more than equilibrium play and stays exploitable for 20% of the pot. The pure best response wins 42% more but is exploitable for 45%.</li>
<li><strong>Opponent model.</strong> Across 24 simulated players, the average error of the estimates falls from 0.077 after 50 hands each to 0.019 after 2,500, about half the error of raw frequencies. The 90% intervals contain the truth 88-93% of the time, and the clustering recovers all six playing styles.</li>
<li><strong>Ranges from actions.</strong> On 1,903 simulated hands, scored on the half not used for fitting, the reconstructed ranges make each player’s true hand twice as likely as a uniform range would, against 1.5 times with population frequencies alone. The 90% most likely part of a range contains the true hand 94% of the time. Treating every action as fully revealing gets that down to 51%: players slow-play and float, so the model counts half of all actions as uninformative, a share fitted on the data.</li>
<li><strong>River review.</strong> Replaying 1,945 heads-up rivers from 6,000 simulated hands against their equilibria, the typical decision costs nothing (the median is zero) and a few cost tens of big blinds. Maniacs give up the most per decision (1.5 big blinds on average) and tight-aggressive players the least (0.7). Decisions the equilibrium would rarely reach are flagged rather than scored, because the solver explores them too little for their numbers to mean much.</li>
</ul>
<p>The full reports, with method, tables and figures, are <a href="https://github.com/RasmusCodes/poker-ecosystem/tree/main/research/reports" target="_blank" rel="noopener">on GitHub</a>.</p>
<h2 id="how-its-built">How it’s built <a class="header-anchor" href="#how-its-built">#</a></h2>
<p>The engine is a Rust workspace of seven crates: cards and ranges, evaluators, equity, the CFR family, the range solver, hand histories, and a command-line tool whose JSON output everything else reads. Its only outside dependencies are serde, serde_json and rayon. The research layer is Python with nothing beyond the standard library: statistics, the opponent model, clustering, a SQLite hand database and the charts. The lab is a JavaScript port of the engine with no build step. The JavaScript and Rust engines are tied together by 26,612 automatic checks, so the browser shows exactly what the Rust code computes; the range probabilities agree to the last bit.</p>
<h2 id="limits">Limits <a class="header-anchor" href="#limits">#</a></h2>
<ul>
<li><strong>It starts on the turn or river</strong> with ranges you give it; there is no preflop or flop solver here. My <a href="https://rasmuscodes.github.io/projects/nlh-solver/">No-Limit Hold’em</a> and <a href="https://rasmuscodes.github.io/projects/plo-solver/">Pot-Limit Omaha</a> solvers cover full flops and preflop.</li>
<li><strong>Bet sizes are an abstraction.</strong> A solution is an equilibrium of the game with the listed sizes; an opponent using other sizes is outside it.</li>
<li><strong>Multiway solving is exact only for small ranges</strong>, and carries no equilibrium guarantee.</li>
<li><strong>The opponent data is simulated.</strong> Real players adapt and are less tidy than the bots, so read the model’s accuracy, and the ranges’ calibration, as a best case.</li>
<li><strong>The river review covers heads-up hold’em rivers</strong>, one board at a time; earlier streets are not reviewed.</li>
<li><strong>Mixed games here means flop games.</strong> Hold’em, Omaha, Omaha Hi-Lo, Big O and Short Deck are covered; stud and draw games are not.</li>
</ul>
<p>It sits next to my <a href="https://rasmuscodes.github.io/projects/nlh-solver/">No-Limit Hold’em solver</a>, my <a href="https://rasmuscodes.github.io/projects/plo-solver/">Pot-Limit Omaha solver</a>, the <a href="https://rasmuscodes.github.io/projects/figgie-bot/">Figgie trading bot</a> and <a href="https://rasmuscodes.github.io/projects/game-tree-studio/">Game Tree Studio</a>.</p>
]]></content:encoded></item><item><title>A cross-asset relative-value scanner: which dislocations are real?</title><link>https://rasmuscodes.github.io/projects/cross-asset-rv/</link><guid isPermaLink="true">https://rasmuscodes.github.io/projects/cross-asset-rv/</guid><pubDate>Mon, 23 Nov 2026 12:00:00 +0000</pubDate><description>191 pricing relationships across ETFs, futures, ADRs, FX, sovereign and corporate bonds, commodities and funding markets, each checked for a convergence mechanism, synchronous prices, costs, borrow and multiple testing before anything is called executable.</description><category>relative value</category><category>arbitrage</category><category>cointegration</category><category>statistical arbitrage</category><category>fixed income</category><content:encoded><![CDATA[<p>Two prices that should move together sometimes don’t. The question that matters is whether a trader could have done anything about it. This scanner searches 191 relationships for dislocations and labels each one by what links the prices:</p>
<ul>
<li><strong>Arbitrage</strong>: a mechanism lets a trader force convergence, such as ETF creation and redemption, cash-and-carry for index futures, depositary conversion of ADRs, cross-border settlement of interlisted shares, or Berkshire’s class A to class B conversion.</li>
<li><strong>Economic link</strong>: there is a reason to converge, but nothing forces it. Examples are share classes without conversion, dual-listed companies, ADRs with conversion limits, calendar and crack spreads.</li>
<li><strong>Statistical</strong>: the prices have co-moved, nothing more. Sector and stock pairs, curve and cross-market bond spreads and carry trades fall here, and the scanner never calls them arbitrage.</li>
</ul>
<p>A signal is called executable only if the legs’ closing prices are synchronous, the deviation clears the no-arbitrage band (fees, stamp duties, transaction taxes, half-spreads, FX), the expected convergence pays for costs, carry, funding and borrow, the short leg can be borrowed, and the spread actually mean-reverts.</p>
<p>Try it below. Filter by asset class or relationship strength, move the entry threshold, and open any relationship to see its spread, hedge ratio, past convergence, costs and risk, or run a hypothetical trade. <em>Build a pair</em> runs the cointegration tests and a backtest in your browser on open government and central-bank data.</p>
<div style="width: min(1240px, calc(100vw - 32px)); position: relative; left: 50%; transform: translateX(-50%); margin: 28px 0 36px;">
<iframe src="https://rasmuscodes.github.io/apps/cross-asset-rv/?v=20261125" title="Cross-asset relative-value scanner" style="display: block; width: 100%; height: 1150px; border: 1px solid var(--rule); border-radius: 12px; background: var(--bg);"></iframe>
</div>
<h2 id="what-i-found">What I found <a class="header-anchor" href="#what-i-found">#</a></h2>
<p>Data runs to 20 November 2026. The same rule, fixed in advance, applies to every relationship: enter at a z-score of 2, exit at 0.5, stop at 4, trade at the next close, conservative costs.</p>
<ul>
<li><strong>Same-close fills invent arbitrage.</strong> If you assume a trade fills at the very close that produced its signal, 73 relationships earn a net Sharpe ratio above 1; arbitrage relationships have a median of 2.2. Fill at the next close, which a trader can actually do, and none is above 1, with a median of -0.40. The apparent profits come from bid-ask bounce at the close, stale fund NAVs and prices taken hours apart. An Asian ADR’s premium predicts the next day’s home-market return (median correlation 0.55), and an international ETF’s “premium” predicts the next NAV change.</li>
<li><strong>Multiple testing removes what is left.</strong> 10 of 181 strategies are positive at the 5% level, about the 9 expected by chance. None survives a Benjamini-Hochberg or Bonferroni correction, and White’s reality check gives the best one a p-value of 0.27.</li>
<li><strong>The cointegration screen finds what chance predicts.</strong> Over the last three years, 52 of 1,221 pairs (4.3%) pass an Engle-Granger test at 5%, while independent random walks pass 5.5% of the time, and one pair survives the correction. Selected pairs did stay cointegrated more often than the base rate (21% against 5%), but traded out of sample they lost money after costs.</li>
<li><strong>Carry is the one consistent earner</strong>, and it is a risk premium, not an arbitrage: 12 of 13 FX carry backtests are positive, with a median Sharpe of 0.29, but none is significant on its own.</li>
<li>Kalman, rolling and 1:1 hedge ratios perform alike once costs are paid; a hedge frozen at formation decays. Gating trades on a regime-switching filter or a Bayesian test of mean reversion changes the median Sharpe by less than 0.02.</li>
</ul>
<p>The report keeps the failures: an FX “triangle” built from two official fixings taken six hours apart, WTI’s April 2020 contango blowing through the full-carry bound because storage ran out, Berkshire’s conversion bound “violated” by closing-print noise, TSMC’s ADR premium that never converges because Taiwan restricts new ADRs, and the corporate actions the price vendor adjusted on one listing but not the other.</p>
<h2 id="how-it-works">How it works <a class="header-anchor" href="#how-it-works">#</a></h2>
<ul>
<li><strong>Data</strong>: 381 instruments from 12 sources. Rates, FX fixings, sovereign yields, money markets and energy come from the US Treasury, Federal Reserve, New York Fed, ECB, Bundesbank, Japan’s Ministry of Finance, Bank of Canada, Reserve Bank of Australia, Bank of England, EIA and OECD. Equities, ETFs, ADRs, futures and indices come from a price vendor, and ETF NAVs from the issuer. Every download is cached with its source, licence and checksum.</li>
<li><strong>Models</strong>: Engle-Granger and Johansen tests with MacKinnon p-values (matched to statsmodels), Kalman-filter hedge ratios, Ornstein-Uhlenbeck half-lives judged with Dickey-Fuller rather than normal critical values, a two-state Markov-switching model, a Bayesian comparison of mean reversion against a random walk, change-point detection and rolling stability tests. The Bayesian part exists because the usual flat-prior posterior reports about 99% “mean reversion” for pure random walks.</li>
<li><strong>Costs and risk</strong>: stress-scaled half-spreads, commissions, square-root market impact, stamp duties and transaction taxes in London, Hong Kong, Taipei, Mumbai, Seoul, Zurich and Paris, FX conversion, ADR conversion fees, funding and borrow, and a full re-trade at every futures roll. Each trade reports its maximum adverse excursion, and each relationship its basis risk, currency exposure, liquidity and capacity.</li>
<li><strong>Validation</strong>: in-sample to 2015 and out-of-sample since, Benjamini-Hochberg, Bonferroni and Holm corrections, deflated Sharpe ratios, White’s reality check, random-walk null rates and rolling formation-to-test persistence. 41 tests cover the models, the engine and the scanners. The browser engine reproduces the Python backtests.</li>
</ul>
<h2 id="limits">Limits <a class="header-anchor" href="#limits">#</a></h2>
<ul>
<li>Daily closing prices only. Synchronised intraday quotes would settle which timing-limited dislocations were real; they aren’t freely available.</li>
<li>Corporate bonds are covered through indices and ETFs, not single bonds, and without FX forwards covered interest parity can’t be measured.</li>
<li>Borrow availability and fees are assumptions by market tier, not locate data.</li>
<li>Vendor prices appear on this page only as derived analytics: spreads, hedged-position P&amp;L and backtest results, never the instruments’ own prices.</li>
</ul>
]]></content:encoded></item><item><title>Combining sixteen equity signals: does complexity pay?</title><link>https://rasmuscodes.github.io/projects/alpha-combination/</link><guid isPermaLink="true">https://rasmuscodes.github.io/projects/alpha-combination/</guid><pubDate>Sun, 22 Nov 2026 12:00:00 +0000</pubDate><description>A pre-registered test of seventeen ways to combine noisy, correlated return signals in the S&amp;P 500 from 1980 to 2024, a second test that adds analyst and options signals, and an interactive lab that runs the same methods in the browser.</description><category>signal combination</category><category>machine learning</category><category>factor investing</category><category>portfolio construction</category><content:encoded><![CDATA[<p>A portfolio manager with many imperfect signals has to decide how to combine them. Machine learning promises to find the right weights, interactions and regimes; equal weighting promises nothing and is hard to beat. I tested seventeen combination methods against equal weights on sixteen published US-equity signals (momentum, reversal, value, quality, investment, low risk and seasonality) in the S&amp;P 500, strictly out of sample and after trading costs. The protocol, hypotheses and decision rule were committed to git before any result existed.</p>
<p>The lab below has three parts. The first shows why ten highly correlated signals are not ten sources of alpha. The second builds a world where you know the truth (pick the signals, their strength and correlations, add non-linearity, regime switches or decay) and runs a full walk-forward comparison of the methods in your browser. The third shows the S&amp;P 500 results.</p>
<link rel="stylesheet" href="https://rasmuscodes.github.io/apps/alpha-combination/lab.css?v=20261124a">
<div data-acl-lab data-wide></div>
<script type="module" src="https://rasmuscodes.github.io/apps/alpha-combination/lab.js?v=20261124a"></script>
<h2 id="what-i-found">What I found <a class="header-anchor" href="#what-i-found">#</a></h2>
<div class="table-wrap"><table>
<thead>
<tr>
<th>Question</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr>
<td>Does any complex method beat equal weights?</td>
<td>Not by the pre-registered rule: no method clears a Holm-adjusted 5% test on net Sharpe or on forecast accuracy</td>
</tr>
<tr>
<td>Do complex models forecast better?</td>
<td>Slightly. Random forests raise the mean monthly rank IC from 0.028 to 0.042; tests that allow for the dependence between methods accept the gain (SPA p = 0.013), the stricter Holm test does not (p = 0.09)</td>
</tr>
<tr>
<td>Do better forecasts make better portfolios?</td>
<td>Not after costs. Flexible models trade about twice as much (10.6-13.5 times the book a year against 6.2), and their net Sharpe gains of 0.1-0.2 are not significant</td>
</tr>
<tr>
<td>What did best after costs?</td>
<td>A mean-variance mix of the signal portfolios: net Sharpe 0.75 against 0.27. A minimum-variance mix that ignores expected returns does as well, so the gain comes from the covariance of the signals, not from forecasting them</td>
</tr>
<tr>
<td>And once market exposure is removed?</td>
<td>Equal weights carries a market beta of about -0.5 from its low-risk signals. Hedged ex ante, its net Sharpe is 0.78 and no method beats it</td>
</tr>
<tr>
<td>Did the edge last?</td>
<td>No. Equal weights’ rank IC fell from 0.037 in 1980-99 to 0.004 in 2015-24, and every method faded with it</td>
</tr>
<tr>
<td>Do analyst and options signals change this?</td>
<td>No. In a second pre-registered test the analyst signals raise equal weights’ rank IC by about a third, but no complex method beats equal weights on 20 or 23 signals, and after 2004 five estimated linear methods do significantly worse once the market is hedged</td>
</tr>
</tbody>
</table></div>
<p><strong>Complexity cut both ways.</strong> Less shrinkage and deeper trees always helped: sixteen weights are well estimated from 350,000 stock-months. More adaptivity always hurt: forgetting factors, regime-specific weights and dynamic model averaging tracked noise. Regressions give the 52-week-high signal a negative weight: it is 58% correlated with momentum and adds nothing alone, so it is used to hedge momentum, against its published sign.</p>
<p><strong>The machinery passes its own test.</strong> On synthetic data with a strong signal, gradient boosting recovers 86% of a non-linear truth where linear models get 58%, and the regime ensemble recovers 98% of a regime-switching one. At realistic signal strength most of these advantages shrink into the noise across seeds, which is what the real data look like.</p>
<p><strong>New information helped equal weights, not complexity.</strong> The obvious objection is that sixteen signals that behave like ten are too similar for a flexible model to find anything. So a second pre-registered test added four I/B/E/S analyst signals (forecast revisions, revision breadth, earnings surprises, forecast dispersion) and three OptionMetrics signals (volatility skew, call-put volatility spread, realized minus implied volatility). With all seven the effective number of independent signals rises from 10 to 14. The analyst signals raise equal weights’ rank IC from 0.018 to 0.024 in 1990-2024 (Holm p = 0.06). The largest complex-method gain, mean-variance’s +0.61 net Sharpe, fails the Holm test (p = 0.21), and much of it is market exposure: hedged, it trails equal weights (0.54 against 0.66). From 2004, with the options signals, every complex method trails equal weights.</p>
<figure class="figure"><img loading="lazy" decoding="async" src="https://rasmuscodes.github.io/media/alpha-combination/sharpe_net_ci.png" alt="Net Sharpe ratio of every method with 95% bootstrap intervals, equal weights marked" /><figcaption>Net Sharpe ratio of every method with 95% bootstrap intervals, equal weights marked</figcaption></figure>
<h2 id="how-it-works">How it works <a class="header-anchor" href="#how-it-works">#</a></h2>
<ul>
<li><strong>Point-in-time data.</strong> S&amp;P 500 members as of each month from CRSP (no survivorship bias, delisting returns included) and Compustat fundamentals usable six months after the fiscal year end. 539 out-of-sample months, 1980-2024. The second test adds unadjusted I/B/E/S forecasts (scaled by same-date prices, blanked across stock splits) and the OptionMetrics volatility surface.</li>
<li><strong>One signal interface.</strong> Every signal arrives as records with instrument, date, horizon, value, confidence, observations, provenance and a code-hash version, so a new signal (or a vendor file) plugs in without code changes.</li>
<li><strong>Seventeen methods</strong> behind one interface: equal and family weights, IC weights, OLS, ridge, lasso, elastic net, principal components, signal mean-variance, Bayesian model averaging over all 65,536 subsets, Bayesian shrinkage toward equal weights, random forests, gradient boosting, dynamic model averaging, a regime-conditioned ensemble and two online learners.</li>
<li><strong>No peeking.</strong> Walk-forward refits every year, hyperparameters chosen by nested validation inside each training window, a one-month embargo, and a test that changes everything after a date and checks no earlier forecast moves.</li>
<li><strong>Statistics for many tests.</strong> Ledoit-Wolf Sharpe tests, Holm, Benjamini-Hochberg and Romano-Wolf corrections, Hansen’s SPA test, deflated Sharpe ratios that count every configuration in an append-only experiment registry, and the probability of backtest overfitting.</li>
</ul>
<h2 id="limits">Limits <a class="header-anchor" href="#limits">#</a></h2>
<ul>
<li>Large caps, monthly horizon, sixteen classic signals (twenty-three in the second test). Machine learning gains are documented to be larger among small stocks and with hundreds of characteristics; this says nothing about that setting.</li>
<li>Trading costs follow an assumed schedule by era, not measured trades, and these monthly full-universe books have small capacity (tens of millions of dollars under a square-root impact model).</li>
<li>The market-hedging and mean-variance decompositions were decided after seeing the main results and are labelled exploratory. The second test made the market hedge confirmatory.</li>
<li>Analyst and options data cover shorter periods, so the second test has 419 months with analyst signals and only 251 with options signals.</li>
</ul>
<h2 id="how-its-built">How it’s built <a class="header-anchor" href="#how-its-built">#</a></h2>
<p>A Python package (NumPy, pandas, scikit-learn, LightGBM) with 41 tests, checkpointed experiment runners and a registry of every run. The lab is a JavaScript port of the methods that runs in a Web Worker; 29 checks confirm it reproduces the Python library’s weights and forecasts to about one part in a trillion. The CRSP, Compustat, I/B/E/S and OptionMetrics data are licensed and not published; the lab shows only portfolio-level results.</p>
]]></content:encoded></item><item><title>A research operating system that catches the mistakes behind good-looking backtests</title><link>https://rasmuscodes.github.io/projects/research-os/</link><guid isPermaLink="true">https://rasmuscodes.github.io/projects/research-os/</guid><pubDate>Sun, 22 Nov 2026 12:00:00 +0000</pubDate><description>An experiment registry, data-provenance layer and statistical validation framework for quant research, shown on a synthetic market where the right answers are known.</description><category>research infrastructure</category><category>reproducibility</category><category>backtesting</category><category>multiple testing</category><category>python</category><content:encoded><![CDATA[<p>Most backtests that look good are wrong for boring reasons: the researcher tried forty variants and reported the best, joined data on a date before it was published, tested on today’s surviving stocks, kept peeking at the holdout, or rewrote the hypothesis after seeing the result. None of that is visible in a Sharpe ratio. I built a research operating system that records every experiment with its hypothesis, data versions, code, parameters and seed, and then checks the record for exactly these failures.</p>
<p>The demo below is a real registry, exported to the browser. It replays two months of research on a synthetic market in which I planted the effects, so every verdict can be checked against the truth. A profitability effect is real, momentum is real but fades, short-term reversal is real only before trading costs, and futures trend rules have no edge at all. The research script also makes the classic mistakes on purpose. Everything is synthetic and the dates are simulated.</p>
<div class="qros-wrap"><iframe id="qros-demo" src="https://rasmuscodes.github.io/apps/research-os/index.html?embed=1" title="Research OS demo: an interactive experiment registry on synthetic data"></iframe></div>
<script>
(function () {
  var frame = document.getElementById("qros-demo");
  if (!frame) return;
  window.addEventListener("message", function (ev) {
    if (ev.origin !== window.location.origin || ev.source !== frame.contentWindow) return;
    var d = ev.data || {};
    if (d.type === "qros-height" && d.height > 300) frame.style.height = Math.ceil(d.height) + "px";
    if (d.type === "qros-navigate") {
      var top = frame.getBoundingClientRect().top;
      if (top < 0) window.scrollBy({ top: top - 90, behavior: "smooth" });
    }
  });
})();
</script>
<style>
.qros-wrap { width: min(1100px, calc(100vw - 48px)); position: relative; left: 50%; transform: translateX(-50%); margin: 28px 0 36px; border: 1px solid var(--rule); border-radius: 12px; overflow: hidden; background: var(--bg); }
.qros-wrap iframe { display: block; width: 100%; height: 1500px; border: 0; background: transparent; }
@media (max-width: 640px) { .qros-wrap { width: calc(100vw - 24px); } }
</style>
<h2 id="what-the-demo-shows">What the demo shows <a class="header-anchor" href="#what-the-demo-shows">#</a></h2>
<div class="table-wrap"><table>
<thead>
<tr>
<th>Lesson</th>
<th>Evidence in the registry</th>
<th>Verdict</th>
</tr>
</thead>
<tbody>
<tr>
<td>A real effect survives every check</td>
<td>The pre-registered profitability strategy, deflated for its five trials and confirmed on the sealed 2020-2024 holdout (Sharpe 0.83, p = 0.03 on the first look)</td>
<td>Robust</td>
</tr>
<tr>
<td>In-sample significance is not robustness</td>
<td>Momentum: deflated Sharpe ratios near 1 in-sample, but the planted effect fades, and the nine variants’ out-of-sample Sharpe ratios range from -0.61 to 0.65</td>
<td>Fragile</td>
</tr>
<tr>
<td>The best of many tries looks good by luck</td>
<td>45 moving-average rules on a contract with nothing to time: the best has a Sharpe of 0.38 but a deflated Sharpe ratio of 0.63, and the probability of backtest overfitting is 0.70</td>
<td>No edge</td>
</tr>
<tr>
<td>Look-ahead is caught from the rows used</td>
<td>Fundamentals joined on the quarter end instead of the publication date: an in-sample Sharpe of 2.7, and an audit trail of every row used early</td>
<td>Invalid</td>
</tr>
<tr>
<td>A hypothesis rewritten after the results proves nothing</td>
<td>“Continuation” failed, was restated as “reversal” with the prediction flipped, and re-tested on the same data</td>
<td>Invalid</td>
</tr>
<tr>
<td>A holdout is spent by looking</td>
<td>Three looks were allowed; looks four to eight, by a researcher checking the best trend rules, are flagged</td>
<td>Invalid</td>
</tr>
<tr>
<td>Survivors, unadjusted prices and unseeded randomness</td>
<td>A survivor-only universe, returns computed from raw prices with splits, and a random tie-break that never reproduces</td>
<td>Invalid</td>
</tr>
</tbody>
</table></div>
<p>The registry grades 75 experiments: 1 robust, 12 fragile, 52 with no edge and 10 invalid. No experiment without a planted effect was graded robust. Real effects can still be graded fragile or no-edge when the evidence is too weak: reversal, for example, is real before costs but not after them.</p>
<h2 id="how-it-works">How it works <a class="header-anchor" href="#how-it-works">#</a></h2>
<ul>
<li><strong>Experiment registry.</strong> A SQLite database records each experiment’s hypothesis and the version it tested, its family of related trials, parameters, seed, code hash, environment, dataset versions, windows, metrics and artifacts. Finished experiments cannot be edited (database triggers refuse it), and every change appends to a hash-chained audit log. The demo’s Audit log tab re-verifies all 793 events in the browser and shows what one edited event does to the chain.</li>
<li><strong>Data provenance.</strong> Datasets are stored as content-addressed versions, with the transforms that derived them, the time each version was known, and point-in-time joins that audit the rows a strategy actually used. Corporate-action adjustment and a split detector catch unadjusted prices.</li>
<li><strong>Validation.</strong> Every strategy gets the same treatment: out-of-sample tests adjusted for every trial evaluated on the same window, the deflated Sharpe ratio, the probability of backtest overfitting, stationary-bootstrap intervals, purged cross-validation, walk-forward selection, parameter-plateau and cost sensitivity, and regime analysis. A transparent scorecard turns these into a verdict anyone can recompute.</li>
<li><strong>Hygiene rules.</strong> 26 rules flag practices that inflate results, from excessive tuning to a holdout opened without declaring it.</li>
<li><strong>Reproducibility.</strong> Managed experiments re-run from the record and compare result hashes. In the Reproduce tab, your browser re-runs a recorded experiment with a JavaScript port of the generator and strategy and gets the same SHA-256 as the Python run.</li>
</ul>
<h2 id="connecting-my-other-projects">Connecting my other projects <a class="header-anchor" href="#connecting-my-other-projects">#</a></h2>
<p>Other repositories report runs through a language-agnostic manifest (JSON plus a returns file), a one-file Python writer or a dependency-free Rust crate, so no code bases are merged. I pointed the adapters at three of my projects without changing their code: 672 simulator runs from the Rust market simulator, 192 reinforcement-learning runs and 53 statistical-arbitrage books. qros re-ran one recorded simulator run from its stored command, and the run reproduced its event digest exactly.</p>
<h2 id="limits">Limits <a class="header-anchor" href="#limits">#</a></h2>
<ul>
<li>The demo market is synthetic and its effect sizes were chosen to be detectable; real markets are less kind.</li>
<li>The thresholds (deflated Sharpe ratio of 0.95, PBO of 0.25, a 5% test after correction) are conventions, recorded with every report, not laws.</li>
<li>The audit log is tamper-evident, not tamper-proof: anyone with write access to the file could rewrite the whole chain, which would change its published head hash.</li>
<li>The deflated Sharpe ratio assumes a family’s trials come from one idea; mixing unrelated strategies in a family distorts it.</li>
</ul>
<h2 id="how-its-built">How it’s built <a class="header-anchor" href="#how-its-built">#</a></h2>
<p>A Python package (NumPy, pandas, SQLite) of about 6,800 lines, with a command-line interface and Python API, 104 tests checked against independent references (statsmodels for the multiple-testing corrections and Newey-West statistics, the published deflated-Sharpe example, standard SHA-256 vectors), and continuous integration on Linux and Windows that also runs the browser code under Node and the Rust crate’s tests. The dashboard is plain JavaScript and SVG with no libraries; its colours are checked for colour-blind separation in light and dark mode.</p>
]]></content:encoded></item><item><title>Reading industrial demand before the earnings release</title><link>https://rasmuscodes.github.io/projects/industrial-intelligence/</link><guid isPermaLink="true">https://rasmuscodes.github.io/projects/industrial-intelligence/</guid><pubDate>Sat, 21 Nov 2026 12:00:00 +0000</pubDate><description>Factory orders, power-plant pipelines, grid load, customers’ capital spending, permits and tenders, mapped to 17 industrial companies and tested point in time. They nowcast revenue slightly better than company history, lead nothing, and predict no excess returns.</description><category>alternative data</category><category>industrials</category><category>nowcasting</category><category>point-in-time</category><category>data centers</category><content:encoded><![CDATA[<p>Industrial Intelligence is a platform that tracks physical economic activity (factory orders, planned power plants, electricity demand, the capital spending of the companies’ customers, construction registrations, utility tenders) and asks whether it tells you an industrial company’s revenue and margins before the company reports them. It covers 17 US-listed equipment makers and contractors, among them Caterpillar, Vertiv, Eaton, GE Vernova, Quanta and the three big chip-tool makers, and maps ABB, Siemens Energy and Schneider Electric without modelling them.</p>
<p>The <a href="https://rasmuscodes.github.io/apps/industrial-intelligence/">interactive dashboard</a> lets you pick a company and inspect its segments, its mapped indicators against reported revenue, a forecast you can change, its historical forecast errors and a dated timeline of contracts, projects and announcements.</p>
<h2 id="how-it-works">How it works <a class="header-anchor" href="#how-it-works">#</a></h2>
<ul>
<li><strong>Sources.</strong> Eighteen sources were probed and ranked by availability, reliability and economic relevance; twelve public ones are used: SEC filings (financials, 879 XBRL documents with segment data, 1,055 press releases), Census factory orders and construction spending with every published vintage, EIA’s monthly power-plant inventory since 2015, hourly grid demand, three grid operators’ interconnection queues, Texas data center registrations, EU utility tenders, job postings and trade flows. Where a site’s robots.txt or terms said no (the BLS API, ERCOT), or a source sits behind a login, it is listed as not used.</li>
<li><strong>Point in time.</strong> Every value carries the moment it became public. Revisions are new rows, not overwrites. Forecasts are made one second before each earnings release, so a model only ever sees what was published by then.</li>
<li><strong>A mapping layer written first.</strong> Each company is linked to the indicators that should drive it, with the segment, the expected timing and the channel, before any model saw the data. Its profile (segments, geography, customers, backlog, pricing, margin drivers) quotes its own 10-K, and all 250 quotes are checked against the filing text by the test suite.</li>
<li><strong>Models and tests.</strong> Baselines (random walk, the company’s own history), a composite of the mapped indicators, a partially pooled Bayesian version, ridge, gradient boosting and backlog models, refit every quarter. 2016–2020 is the development period and 2021–2026 the holdout. Diebold-Mariano and Clark-West tests treat each quarter as one observation.</li>
</ul>
<h2 id="what-it-found">What it found <a class="header-anchor" href="#what-it-found">#</a></h2>
<figure class="figure"><img loading="lazy" decoding="async" src="https://rasmuscodes.github.io/media/industrial-intelligence/cover.svg" alt="Bar chart of nowcast error relative to company history by case study, 2021 to 2026" /><figcaption>Bar chart of nowcast error relative to company history by case study, 2021 to 2026</figcaption></figure>
<ul>
<li><strong>A small, real nowcast gain.</strong> Just before the release, the indicator model misses reported revenue growth by 7.39 percentage points on average in the holdout, against 7.50 for the company’s own history and 7.82 for a random walk. The indicators carry information history lacks (Clark-West p = 0.002), but the accuracy gain is too small to be significant on its own (Diebold-Mariano p = 0.23), and there was none in 2016–2020.</li>
<li><strong>Where it works:</strong> data center suppliers, grid equipment, chip-tool makers (2–4% better in the holdout). Not for Caterpillar, Cummins and United Rentals (3% worse).</li>
<li><strong>Coincident, not leading.</strong> One or two quarters before a release the indicators add nothing. Their information arrives with the quarter itself.</li>
</ul>
<figure class="figure"><img loading="lazy" decoding="async" src="https://rasmuscodes.github.io/media/industrial-intelligence/horizons.svg" alt="Bar chart of error relative to the history-only model at three horizons: 0.99 at the nowcast, 1.00 one quarter earlier, 1.02 two quarters earlier" /><figcaption>Bar chart of error relative to the history-only model at three horizons: 0.99 at the nowcast, 1.00 one quarter earlier, 1.02 two quarters earlier</figcaption></figure>
<ul>
<li><strong>A careless backtest would have said more.</strong> On today’s revised data with no publication lags, the holdout gain reads 2.6% instead of 1.5%.</li>
<li><strong>More model is worse.</strong> Gradient boosting was 14% worse than company history and a ridge on every indicator 24% worse: 650 company-quarters is not enough data for them.</li>
<li><strong>No excess returns.</strong> The indicators’ extra information predicted neither earnings-day returns nor the drift into the release (CRSP data through 2024, 12 companies). Predicting revenue and predicting the stock are different questions, and only the first got a positive answer.</li>
</ul>
<h2 id="four-case-studies">Four case studies <a class="header-anchor" href="#four-case-studies">#</a></h2>
<ul>
<li><strong><a href="https://github.com/RasmusCodes/industrial-intelligence/blob/main/docs/case_studies/01_data_center_power_cooling.md" target="_blank" rel="noopener">Data center power and cooling</a>.</strong> Hyperscaler capex appears to lead Vertiv’s revenue by two quarters in sample, but out of sample the lead disappears; HVAC orders and cloud capex help the nowcast slightly.</li>
<li><strong><a href="https://github.com/RasmusCodes/industrial-intelligence/blob/main/docs/case_studies/02_caterpillar_equipment_demand.md" target="_blank" rel="noopener">Caterpillar equipment demand</a>.</strong> The composite fails, mostly because sales follow dealer inventories. One series, US construction-machinery orders, leads by about a quarter at every horizon, but does not survive a multiple-testing correction: a hypothesis for the next earnings seasons.</li>
<li><strong><a href="https://github.com/RasmusCodes/industrial-intelligence/blob/main/docs/case_studies/03_electrical_equipment_grid.md" target="_blank" rel="noopener">Electrical equipment and grid</a>.</strong> Utility capex is too smooth to be a quarterly signal, and price indexes do not beat simple mean reversion for margins.</li>
<li><strong><a href="https://github.com/RasmusCodes/industrial-intelligence/blob/main/docs/case_studies/04_backlog_conversion.md" target="_blank" rel="noopener">Order backlogs and conversion</a>.</strong> Backlogs grew faster than revenue at all ten companies that report them, so every backlog-to-revenue rule fails; the indicators do track implied order intake.</li>
</ul>
<h2 id="limits">Limits <a class="header-anchor" href="#limits">#</a></h2>
<ul>
<li>No consensus estimates are licensed, so “surprise” means surprise against a statistical baseline, not against the market.</li>
<li>Some series exist only as revised history (Census data center construction, grid load); for them the backtest assumes a publication lag and cannot replay revisions.</li>
<li>UN Comtrade’s anonymous quota cut the trade series short, satellite data need accounts the project does not have, and companies outside the SEC’s quarterly XBRL (ABB, Siemens Energy, Schneider) are mapped but not modelled.</li>
<li>17 companies and about 40 quarters each is a small sample: company-level results are noisy.</li>
</ul>
<h2 id="how-its-built">How it’s built <a class="header-anchor" href="#how-its-built">#</a></h2>
<p>A Python package with one polite HTTP client for every source (robots.txt, throttling, a raw cache with checksums), a point-in-time store, an XBRL replay that derives each quarter in the order filings were accepted, and a walk-forward engine with a leakage audit. 41 tests cover the replay, the as-of feature engine, the statistics and the parsers, and recompute sampled features from raw observations to check the point-in-time logic. The dashboard is static: everything it shows is exported as JSON, so it runs without the repository.</p>
]]></content:encoded></item><item><title>Does smart order routing pay? A simulated market and eleven routers</title><link>https://rasmuscodes.github.io/projects/smart-router/</link><guid isPermaLink="true">https://rasmuscodes.github.io/projects/smart-router/</guid><pubDate>Sat, 21 Nov 2026 12:00:00 +0000</pubDate><description>A latency-aware simulation of five trading venues, routers from naive to optimised, and pre-registered experiments on what actually saves money. The simulator runs in your browser below.</description><category>market microstructure</category><category>order routing</category><category>simulation</category><category>python</category><content:encoded><![CDATA[<p>A US stock trades on more than a dozen exchanges and dozens of dark pools, each with its own fees, rebates, queue lengths and distance from your servers. A smart order router decides where every child order of a large trade goes. Vendors sell that as a source of savings; the obvious objection is that displayed prices are equal across venues most of the time, and what differs (fees, queues, the odds that a quote is still there when your order arrives, who you end up trading with) is hard to see.</p>
<p>So I built a market where all of that is explicit, and asked a narrow question: <strong>once fees, rebates, queue position, latency, fill probability, adverse selection and market impact are all counted, does intelligent routing still save money, and which part of it does?</strong> I wrote the hypotheses, the metric and the decision rules down before running the evaluation.</p>
<h2 id="try-it">Try it <a class="header-anchor" href="#try-it">#</a></h2>
<p>The box below runs the actual research code: the Python simulator, compiled to WebAssembly by Pyodide, in a background thread of your browser. Pick a market, an order and the routers to compare. Every router faces the same seed, so the differences are the routers’ doing. Seeds 1 to 300 are the experiment’s evaluation seeds, and a 20,000-share order on the default settings reproduces the report’s numbers exactly.</p>
<div id="sor-demo" data-base="/apps/smart-router/"><p>Loading the demo needs JavaScript. The full results are in the <a href="https://github.com/RasmusCodes/multi-venue-smart-router/blob/main/reports/RESULTS.md" target="_blank" rel="noopener">report on GitHub</a>.</p></div>
<link rel="stylesheet" href="https://rasmuscodes.github.io/apps/smart-router/sor-demo.css">
<script src="https://rasmuscodes.github.io/apps/smart-router/sor-demo.js" defer></script>
<h2 id="what-i-found">What I found <a class="header-anchor" href="#what-i-found">#</a></h2>
<p>Nine pre-registered comparisons, each over 300 seeds paired by seed, with Holm-corrected p-values. I called a saving <em>material</em> if it was at least 0.25 bps (about $6 million a year for a desk trading $1 billion a day) and significant.</p>
<figure class="figure"><img loading="lazy" decoding="async" src="https://rasmuscodes.github.io/media/smart-router/routing_effects.svg" alt="Paired differences in shortfall for each pre-registered comparison, with 95% intervals; the shaded band marks the 0.25 bps materiality bar." /><figcaption>Paired differences in shortfall for each pre-registered comparison, with 95% intervals; the shaded band marks the 0.25 bps materiality bar.</figcaption></figure>
<ul>
<li><strong>For orders that cross the spread, routing pays, and the reason is latency.</strong> A naive router sends child orders to every venue showing the best price at once. Its first fill, on the nearest venue, makes fast market makers pull their quotes elsewhere within microseconds, so 19% of the liquidity it saw is gone when its slower orders arrive. Timing the sends so that every order lands at the same moment cut that to 2% and saved <strong>0.69 bps</strong> [0.66, 0.72], cheaper on 99% of seeds. Ranking venues by fees alone saved 0.11 bps, because the cheapest venues are the slowest and their quotes fade first.</li>
<li><strong>For resting orders, routing pays less, and rebates are a trap.</strong> The full smart router beat posting on the primary exchange by <strong>0.31 bps</strong> [0.23, 0.39] on a patient schedule. Choosing the venue by expected cost (queue ahead, fees, fill odds, the cost of crossing later) saved 0.23 bps, just under my bar. Chasing the biggest maker rebate <em>cost</em> 0.06 bps: orders there filled mostly when the price was about to move through them.</li>
<li><strong>What did not pay.</strong> Splitting each slice across venues with the Cont–Kukanov optimal-placement model did not beat resting on the single best venue (−0.08 bps, not significant). On an urgent schedule the smart router’s edge over naive posting (−0.19 bps) was not significant. Learning venue quality from scratch within one order, by Thompson sampling, did not help either.</li>
<li><strong>The checks held.</strong> The smart router’s gain survived four other markets (access fees capped at $0.0010, faster quote fading, double the volatility, triple the latency gaps: 0.30 to 0.52 bps), and disappeared with four identical venues, where it was 0.12 bps <em>worse</em>: extra machinery only costs when there is nothing to route around.</li>
</ul>
<figure class="figure"><img loading="lazy" decoding="async" src="https://rasmuscodes.github.io/media/smart-router/fades.svg" alt="Share of displayed liquidity gone when an order arrived, by sweep design." /><figcaption>Share of displayed liquidity gone when an order arrived, by sweep design.</figcaption></figure>
<figure class="figure"><img loading="lazy" decoding="async" src="https://rasmuscodes.github.io/media/smart-router/markouts_by_venue.svg" alt="Ten-second markout of passive fills by venue." /><figcaption>Ten-second markout of passive fills by venue.</figcaption></figure>
<p>Where a resting order fills matters as much as whether it fills. Fills on the high-rebate venue were followed by the price moving against them; fills on the inverted venue and on the speed-bump venue, which withdraws stale resting orders before latency arbitrageurs arrive, were followed by favourable moves. That is the pattern Battalio, Corwin and Jennings (2016) document on US exchanges.</p>
<p>The biggest lever was not the venue at all: resting first instead of crossing the spread saved about 3.8 bps, twelve times what venue choice added. In this model resting orders carry no permanent price impact, so that number is an upper bound, and I treat the venue comparisons at a fixed tactic as the result.</p>
<h2 id="how-it-works">How it works <a class="header-anchor" href="#how-it-works">#</a></h2>
<ul>
<li><strong>The market.</strong> Four lit venues and a dark pool, modelled on US market structure but fictional: a maker-taker primary exchange, a high-rebate exchange, an inverted exchange that pays takers, a low-fee exchange with a 350-microsecond speed bump, and a dark midpoint pool that prices off a stale quote. Every venue matches by price-time priority. A hidden fair value moves with news and with order flow.</li>
<li><strong>The other traders.</strong> Market makers quote where their edge after fees allows, so the high-rebate venue gets long queues and the inverted one short ones, and they react to news and to trades on other venues within tens of microseconds. Uninformed traders route by fees or by displayed size. Latency arbitrageurs race the market makers for quotes that news has made stale, and win about a fifth of all volume, close to what Aquilina, Budish and O’Neill (2022) measured on the London Stock Exchange.</li>
<li><strong>The router’s view.</strong> A router sees each venue’s book as it was one network delay ago, and its orders and cancels take 150 to 380 microseconds to arrive.</li>
<li><strong>The routers.</strong> Eleven configurations of one executor with a shared schedule: naive, fee-aware, synchronised and model-based sweeps for crossing the spread; primary, rebate, queue-aware and Thompson-sampling venue choice for resting; the Cont–Kukanov split; and a smart router that combines them. The model-based ones learn only from separate training seeds.</li>
<li><strong>The test.</strong> Every router runs on the same seeds with common random numbers: the same news and the same background orders, until its own orders change the market. That makes a router’s difference from another 30 times less noisy than its raw cost.</li>
</ul>
<h2 id="limits">Limits <a class="header-anchor" href="#limits">#</a></h2>
<ul>
<li>One stylised stock and five stylised venues. The parameters reproduce qualitative facts from the empirical literature (one-tick spreads, longer queues where rebates are higher, a fifth of volume in latency races, quote fading), not one stock’s data, so the magnitudes belong to this market.</li>
<li>Market makers follow fixed rules and never learn about the router, and resting orders have no permanent impact.</li>
<li>Every router uses the same time schedule; scheduling itself is not optimised.</li>
</ul>
<h2 id="how-its-built">How it’s built <a class="header-anchor" href="#how-its-built">#</a></h2>
<p>A pure-Python package with no dependencies for the simulator and routers, so the same code runs in the browser. Runs are bit-identical across platforms: the simulation uses only basic floating-point arithmetic (logarithms included) and platform-stable random streams, and fingerprints of reference runs are locked in tests, which also show that the browser demo reproduces them. The 49 tests include a differential test of the order book against a naive reference over 12,000 random operations and a check of the Cont–Kukanov solver against brute force. The experiments, about 9,400 simulated parent orders, run in 20 minutes on a laptop.</p>
]]></content:encoded></item><item><title>A credit and capital-structure lab</title><link>https://rasmuscodes.github.io/projects/credit-lab/</link><guid isPermaLink="true">https://rasmuscodes.github.io/projects/credit-lab/</guid><pubDate>Sat, 21 Nov 2026 12:00:00 +0000</pubDate><description>Reading a company’s default risk off every security it has issued, with an interactive bankruptcy waterfall built from the filings.</description><category>credit</category><category>capital structure</category><category>distressed debt</category><category>convertibles</category><content:encoded><![CDATA[<p>A company’s loans, bonds, convertibles, preferred stock, equity, CDS and options are all claims on the same assets. If the markets for them price the company’s default risk differently, one of them is wrong, or the difference pays for something else. This lab models the capital structure from the filings, prices every security on one asset process, and compares the result with what each market implies.</p>
<p>Pick a company below, move the value it is worth in a default, and watch who gets paid. The sliders change leverage, maturities, the asset value and volatility, bankruptcy costs and departures from absolute priority; the simulation runs 2,000 default scenarios through the waterfall.</p>
<link rel="stylesheet" href="https://rasmuscodes.github.io/apps/credit-lab/lab.css?v=cca88c6e59">
<div id="credit-lab" class="clab"></div>
<script type="module" src="https://rasmuscodes.github.io/apps/credit-lab/lab-app.js?v=cca88c6e59"></script>
<h2 id="what-the-case-studies-found">What the case studies found <a class="header-anchor" href="#what-the-case-studies-found">#</a></h2>
<p>Market data from the close of 20 November 2026; balance sheets from the latest 10-Q or interim statements.</p>
<ul>
<li><strong>CoreWeave.</strong> The senior notes recover 35% in the central default scenario (21-50% across the range) after the SPV term loans take their GPU collateral and the notes share the operating subsidiaries with trade and lease claims. At that recovery the notes imply a 60% chance of default within five years; a structural model calibrated to the equity says 65% and prices the notes 5-8 points below where they trade. The Jan-2029 $5 puts cap the risk-neutral default probability by then at 16%, against 32-34% implied by the notes.</li>
<li><strong>Strategy.</strong> Its assets are mostly bitcoin, so the asset value the models usually have to guess can be measured. Priced off the observed assets and their volatility, the model values the equity within 1.5% of the market. Calibrated the usual way, from the equity, it gets assets 22-35% too low and asset volatility twice too high.</li>
<li><strong>Wolfspeed’s 2025 bankruptcy.</strong> The engine reproduces the court-filed liquidation analysis exactly. The confirmed plan then gave unsecured creditors 25-30%, where strict priority at the plan’s own valuation gave about 1%: make-wholes, a rights offering, trade claims paid in full and a 5% gift to old shareholders are what negotiation adds.</li>
<li><strong>Nebius and IREN.</strong> Their convertibles imply at most 26-51% five-year default probabilities; equity-calibrated structural models say 73-75%.</li>
</ul>
<p>None of these gaps is an arbitrage. Each signal in the lab’s scanner lists what can keep it open: stale or thin bond prices, recovery uncertainty, the cost of shorting bonds, illiquid options, and answers that depend on the model.</p>
<h2 id="how-it-works">How it works <a class="header-anchor" href="#how-it-works">#</a></h2>
<ul>
<li><strong>The waterfall</strong> splits value across legal entities, lets collateral pay its secured lenders, gives recourse lenders deficiency claims, handles guarantees, subordination with turnover, lease-rejection caps and bankruptcy costs, and can carve out a gift to equity.</li>
<li><strong>Structural models</strong>: Merton, Black-Cox and CreditGrades, plus a pricer that values every claim of a real waterfall on one asset process, exact to quadrature.</li>
<li><strong>Reduced-form models</strong>: hazard curves from bonds, an ISDA-style CDS converter that matches Markit’s CoreWeave quote to 0.02 points, convertibles with jump to default, and model-free default bounds from deep puts.</li>
<li><strong>History</strong>: rating-transition matrices and default rates from S&amp;P’s regulatory filing, compared with what the markets imply.</li>
</ul>
<h2 id="limits">Limits <a class="header-anchor" href="#limits">#</a></h2>
<p>Structural models need an asset value nobody observes, and assume lognormal assets and a static debt stack; real bankruptcies are negotiated. Bond prices are last trades, the CDS curve is one documented point, and recoveries move most with a judgment input, the value at default. The documentation sets out where each of these bites.</p>
]]></content:encoded></item><item><title>Beating Jane Street at their own game</title><link>https://rasmuscodes.github.io/essays/teaching-a-bot-to-trade-figgie/</link><guid isPermaLink="true">https://rasmuscodes.github.io/essays/teaching-a-bot-to-trade-figgie/</guid><pubDate>Fri, 20 Nov 2026 12:00:00 +0000</pubDate><description>I built a bot for Figgie, Jane Street’s trading game. Fifteen versions and 142 live rounds later it beats figgie.com’s Hard bots: what worked, what didn’t, and how it works.</description><category>trading</category><category>game theory</category><category>bots</category><content:encoded><![CDATA[<h2 id="introduction">Introduction <a class="header-anchor" href="#introduction">#</a></h2>
<p>Figgie is a trading game by Jane Street. Four players each put $50 in the pot and are dealt ten cards from a 40-card deck. One suit has 12 cards, two have 10 and one has 8, and nobody knows which is which, you have to guess what is the 12-card suit. The suit of the same colour as the 12-card suit is the goal suit. So if there are 12 clubs, there are either 10 or 8 spades, and that’s the goal suit.</p>
<p>For four minutes, anyone can bid for or offer any suit, and anyone can take a bid or an offer. When the round ends, each goal-suit card pays $10 from the pot, and whoever holds the most goal cards takes the rest: $100, or $120 when the goal suit has eight cards.</p>
<p>Read more on <a href="https://www.figgie.com/how-to-play" target="_blank" rel="noopener">figgie.com/how-to-play</a>.</p>
<p><img src="https://rasmuscodes.github.io/media/teaching-a-bot-to-trade-figgie/02-deck.svg" alt="Diagram of an example Figgie deck: spades 12 cards, clubs 10 cards highlighted as the goal suit, hearts 10 cards, diamonds 8 cards, with the three steps of a round." />
<em>Illustration made with Claude</em></p>
<p>At its core, it’s really just a game of imperfect information, just like the stock market. Your hand may hint at which suit has 12 cards; if you have 1 spade, 5 clubs, 2 hearts and 2 diamonds, based on those cards, it’s more likely that the goal suit is spades.</p>
<p>You can’t know that for certain, though. It could be that the other players have 5 clubs combined, and the goal suit is actually hearts, for example. That is where the trading comes in; every bid, offer, and trade gives some information away. A good player counts cards, reads the market, and trades on their own conviction faster than others.</p>
<p>Two weeks ago, I started playing the game, and quickly was able to beat the hard bots for a modest average profit (~$20-30 per round). I had done some coding before, so I figured I could vibe-code a bot that could beat them more efficiently. The strategy is about 4,400 lines of Python, plus a 2,900-line JavaScript version that runs in the browser. It took 15 versions of the bot, where I kept looking for leaks in the bots’ strategies and my own strategy.</p>
<p>Next I’ll go over the history of developing a winning trading bot and what I learned along the way.</p>
<h2 id="v1-great-at-statistics-horrible-at-trading">v1: great at statistics, horrible at trading <a class="header-anchor" href="#v1-great-at-statistics-horrible-at-trading">#</a></h2>
<p>v1 started by doing the maths right. It updated its probabilities for all 12 decks on every trade, valued each card from them, and made markets around those values, bidding a little below and offering a little above.</p>
<p>Calculating those percentages is only one half of the story, though. It still sucked at trading. When v1’s bid was hit, it was usually because the seller knew the suit was dead. Similarly, when the other bots bought from it, the buyer usually knew it was the goal.</p>
<p>→ This is what’s known as adverse selection, which is one of the central risks of being a market maker even if you can come up with very accurate bids and asks with the data available to you. The trades you get are the ones the other side wanted. v1 ignored the information that the trades conveyed, so it actually lost money to adverse selection and inventory risk. It lost $261 over nine rounds.</p>
<h2 id="the-fix-listening-to-the-market">The fix: Listening to the market <a class="header-anchor" href="#the-fix-listening-to-the-market">#</a></h2>
<p>Realizing this fundamental flaw, I redesigned it to analyze the other players better. v2 treats the highest price anyone bids or pays for a suit as a vote that it’s the goal, and a low offer as a vote against. It also stopped being eager. Its bids start low and climb a dollar every three seconds, and it takes someone else’s quote only with a 20% edge. v2 made $25 a round.</p>
<p>However, it sold its cards too early, before the market had revealed the goal. v3 was more patient with its trading, realizing that there is time value in holding a card. A spade may seem worthless in the beginning if hearts bid for high amounts, but may in fact be the goal suit. It’s kind of like theta in options. v3 only sold when a bid beat the value of keeping the card, including the option value of waiting for the market to reveal the goal. It was the first version with a statistically clear profit: $42 a round, with eight of ten rounds in profit.</p>
<p>I kept iterating, learning from the bots’ past mistakes. By v6, I had run enough sample rounds to fit the signal instead of guessing it. Jane Street’s bots bid $10 to $15 for dead suits all the time, so only bids above about $17 really single out the goal. v7 scores bids that way. It also counts a bid only once it has stood on the book in two different seconds, so a bid flashed and cancelled can’t move it. That’s kind of like spoofing in real markets, where some players trick the algorithms by placing large orders they plan to cancel before they fill (highly illegal market manipulation btw), and I wanted to be protected against it (it’s not illegal in a trading game with fictional money :D)</p>
<p>v8 found the strongest signal. Every Hard bot bids the goal suit up at some point in a round, while a dead suit usually draws a big bid from only one of them. So the lowest of the three bots’ top bids for each suit is a near-perfect tell: in ten rounds it was $7 to $10 for the goal and $3 to $6 for every dead suit. One bluffer can’t fake that.</p>
<p><img src="https://rasmuscodes.github.io/media/teaching-a-bot-to-trade-figgie/04-belief.svg" alt="Line chart of the bot's probability for each suit over one four-minute round. The lead changes hands between diamonds, clubs and hearts until about 2:30; then diamonds climb past 90% at 3:17 and end at 100%." />
<em>The probabilities vary vastly in every round, and are constantly updated with every new bid, offer, and trade.</em></p>
<p><img src="https://rasmuscodes.github.io/media/teaching-a-bot-to-trade-figgie/05-reading.svg" alt="Column chart of the share of rounds in which the bot was at least 90% sure of the goal by the bell: 20% to 60% for v2 to v7, 60% to 100% from v8 on." />
<em>From v8 on, the bot was at least 90% sure of the right suit by the bell in most rounds.</em></p>
<p>Then came the surprise. v8 finished every round with the right suit as its favourite, at 97% on average against v7’s 74%, and its profit didn’t move: $33.50 a round, inside the noise of every version since v3. Knowing the answer at the bell is worth very little. The money is made in the first two or three minutes, while the answer is still uncertain. v9 attacked that window from the other side: early in a round, whoever buys from the bot probably knows more than it does, so its offers are priced as if the buyer does.</p>
<h2 id="chasing-the-sixth-card">Chasing the sixth card <a class="header-anchor" href="#chasing-the-sixth-card">#</a></h2>
<p>With a 10-card goal suit, five cards can only tie for the majority, and six win it. The bot kept stopping at five, and the other bots kept collecting the strays: in seven rounds of v3 and v4 the bonus was split 5-5, leaving $350 on the table. So v5 valued the bonus as if a rival would end up with every goal card the bot lacked, which made the sixth card worth chasing. Think about it: if the goal suit has 10 cards, five cards and a 5-5 split get you $100, while six get you $160. Of course, the goal suit may also have 8 cards, so 5 cards would already be the majority. The bot has to take the probability that the goal suit is 8 cards into consideration, too.</p>
<p>v5 got the sixth card twice, but the same assumption made small holdings look worthless, so it sold the goal cards it was dealt, cheaply: $16 a round, my worst version since v1. v6 kept the idea only for when the bot already holds half the goal suit, and took the whole bonus in 5 of 10 rounds.</p>
<h2 id="an-exploit-hiding-in-the-logs">An exploit hiding in the logs <a class="header-anchor" href="#an-exploit-hiding-in-the-logs">#</a></h2>
<p>From v9 on, the bot logged every quote and trade. Reading the logs turned up a habit of Jane Street’s bots. When a bot offered or sold a card for $1 or $2, another bot usually bid the same suit back up to $4 or more, typically 11 to 12 seconds later. It made no sense to me, so I added a feature that is quite literally “buy low, sell high.” For whatever reason, the bots sell some ‘dead’ cards for super cheap, but end up buying them back. They should have 0 value, assuming that all the bots have the same opinion of the goal suit (definitely not a given!)</p>
<p>v10 buys those cards and resells them. Being wrong about a pattern like that is the real risk, but in my test runs, the inventory risk of ending up owning worthless suits when the bell rings was far outweighed by the profits of reselling those for a higher price. The bot holds only a few unsold cards at a time, counts its own resales double when it judges the pattern, and shuts the exploit off for the round after two net failures or $6 lost.</p>
<p>Live, it worked from the first round. Resale made $73 over v10’s ten rounds, $153 over v11’s, $203 over v12’s and $163 over v13’s, across more than 300 resales, none of them sold at a loss. That is just pure profit made from the bots’ irrationality.</p>
<p>I wanted the bot to find the pattern itself. v12 replaces the hand-written rule with a learner. Every offer another player shows at $5 or less is a question the tape answers within seconds: had the bot bought that card, would someone have bid $2 more for the suit within 45 seconds? So every offer at the table is a labelled example, not only the bot’s own trades. An online Bayesian logistic regression learns the answer from generic features such as the price, the time left, recent bids and the seller’s recent offers. Starting from nothing, it rediscovered “$2 or less resells” within its first live round, and that became its strongest feature. At <a href="http://figgie.com" target="_blank" rel="noopener">figgie.com</a> that only matches the rule I’d found by hand. The point is the next table, where the rule is wrong: the learner adjusts and the rule doesn’t.</p>
<h2 id="fighting-against-overfitting">Fighting against overfitting <a class="header-anchor" href="#fighting-against-overfitting">#</a></h2>
<p>To make sure I’m not just overfitting against these specific bots, I wrote my own bots that tried various patterns to try to exploit my bot. Up to v12 the simulator’s opponents were mostly benchmarks the bot was built to beat. For v13 I wrote opponents built to beat it: a spoofer that flashes big bids on dead suits, rings that fake the resale pattern, a “pump” ring that trades a dead suit among itself at $18 so the tape shows everyone paying up, a sniper, a front-runner, a buyer that never shows a bid, and one that learns what the bot will pay. A test bench, the arena, plays every change in paired sessions at 21 tables, with separate seeds for tuning, choosing and reporting. It scores a change by half its average gain and half its gain over the worst quarter of tables, so a change has to help broadly.</p>
<p>The pump ring took $63 a round: the bot was 98% sure of the decoy after 30 seconds. So v13 learns at every bell, from the revealed goal, how far to trust each of its market readings at this table, and a signal that lies there fades within a round or two. That fixed the belief but not the money. Three colluders who know the goal still take about $60 a round, because they sell the bot dead cards and buy its goal cards whatever it believes. With its market reading switched off entirely, it loses about as much. Some opponents can’t be beaten, and it helps to know which.</p>
<p>In developing the bot, I ran a grand total of 142 live rounds against Jane Street’s bots: +$6,958 in play money, $49 a round on average. Every live test since v3 has been profitable. Over the last 41 rounds (v11 to v13.3) it averaged $81 a round, ±$18 at 95% confidence, with 34 of 41 rounds in profit.</p>
<h2 id="how-it-works-now">How it works now <a class="header-anchor" href="#how-it-works-now">#</a></h2>
<p>There are 12 possible decks, so the bot constantly uses Bayes’ rule (how likely its own hand is under each deck, times how likely everything the market has shown is). Adding up the decks by goal suit gives its probability that each suit is the goal.</p>
<p>Then it values every card: $10 times the chance its suit is the goal, plus what the card does to its share of the majority bonus, given everyone’s likely holdings. And it trades on those values: it takes a bid or offer only when the gain beats $1 plus 20% of the card’s value, and it never sells a card for less than the value of waiting for the market to reveal the goal.</p>
<p>Three parts of the bot are Bayesian: the deck probabilities above, and two learners that update as it plays.</p>
<ul>
<li><strong>The reading learner</strong> decides which market signals to trust. After every round it checks each signal, such as “the suit every bot bids up is the goal”, against the goal that was revealed, and updates its trust in it by Bayes’ rule. Signals that mislead count for less.</li>
<li><strong>The resale learner</strong> decides which cheap cards to buy. It’s a Bayesian logistic regression: every cheap offer on the table is a yes-or-no example (did someone bid the suit back up within 45 seconds?), and it updates after each one. The bot buys only when even a cautious estimate says the resale pays. That’s how it found the “$2 or less resells” rule by itself, in its first round.</li>
</ul>
<p><img src="https://rasmuscodes.github.io/media/teaching-a-bot-to-trade-figgie/how-it-works-moment.svg" alt="Diagram of one real moment, 3:17 into a live round. 1, what it sees: its hand (3 hearts, 7 diamonds), the highest bid on each suit and the lowest of the three bots' top bids (diamonds $8). 2, which deck is it: the chance each suit is the goal from its hand alone (diamonds 49%) and after the market too (diamonds 95%). 3, what a card is worth: a spare diamond about $9.50. 4, what it does: sells a heart into a $4 bid, buys a $2 spade to resell, sells a spare diamond for $16. A reading learner feeds step 2 and a resale learner feeds step 4; the deck step and both learners are marked Bayes." />
<em>One real moment from a live round, 3:17 in: what the bot saw, what it concluded and what it did in the next three seconds. The parts marked Bayes are the Bayesian ones.</em></p>
<h2 id="what-i-learned">What I learned <a class="header-anchor" href="#what-i-learned">#</a></h2>
<ol>
<li>
<p>Adverse selection. Always in trading, there is the risk that your counterparty knows something you don’t. Perfect arithmetic on your own information loses to people trading on theirs, if that information is better. Before asking what a card is worth, ask why someone is willing to trade it with you.</p>
</li>
<li>
<p>Bids, offers, and trades are information. The biggest gains came from reading other players’ bids, and the cleanest signal came from looking at the bids player by player instead of pooled. There are different players in the market with their own information, which may be vastly different from your information. Use their trades as information.</p>
</li>
<li>
<p>“Everybody has a plan until they get punched in the mouth” - Mike Tyson. Just running those calculations isn’t the key to making profits; you need to be able to trade on it and adapt quickly if your forecast is wrong.</p>
</li>
<li>
<p>Separating noise from actual results. Ten live rounds can’t tell a $10 improvement from luck. Paired simulations, replays of logged rounds and keeping separate data for tuning and for testing paint a better picture.</p>
</li>
<li>
<p>Trading games are fun! I still really enjoy playing it and even watching my bot play.</p>
</li>
</ol>
<h2 id="how-i-built-it">How I built it <a class="header-anchor" href="#how-i-built-it">#</a></h2>
<p>I have made some smaller programs when I was younger, but with this project I knew that I don’t have the programming skills yet to do anything of this scale.</p>
<p>I vibe-coded this with Claude Code. It wrote most of the code and ran the simulations and live tests. My involvement was looking at what mistakes the bots were making, how my bot responded to those, and thinking of ways to exploit them. Reselling dead suits and becoming more unexploitable were my ideas, which turned out to be great. Working this way made it fast. Of course, it’d be great to be able to program these things myself, but I think that the whole paradigm of software development is coming closer to a model like this where the human just provides ideas and reasoning to the AI, and the AI implements them.</p>
<p>Developing it, going back-and-forth, took around one week. The most time-consuming part was coming up with ideas on how to extract more and more value (alpha?) from the bots. Some time went to making sure that the trade execution worked and that the bot could run autonomously.</p>
<h2 id="see-it-for-yourself">See it for yourself! <a class="header-anchor" href="#see-it-for-yourself">#</a></h2>
<p>The code, every live round and the analysis tools are on GitHub at <a href="https://github.com/RasmusCodes/figgie-bot" target="_blank" rel="noopener">github.com/RasmusCodes/figgie-bot</a>, under the MIT licence. If you run the userscript, keep it to private tables against <a href="http://figgie.com" target="_blank" rel="noopener">figgie.com</a>’s bots, and check the site’s terms first.</p>
<p>I am not affiliated with Jane Street (yet 😒) in any way. I do have a Jane Street T-shirt from one of their info sessions I attended, and I solved their monthly puzzle :D</p>
]]></content:encoded></item><item><title>Statistical arbitrage on the S&amp;P 500: what survives costs</title><link>https://rasmuscodes.github.io/projects/statarb/</link><guid isPermaLink="true">https://rasmuscodes.github.io/projects/statarb/</guid><pubDate>Thu, 19 Nov 2026 12:00:00 +0000</pubDate><description>A point-in-time research platform for pairs trading, momentum and fundamental signals in S&amp;P 500 stocks, with fourteen research notes, most of them pre-registered.</description><category>statistical arbitrage</category><category>pairs trading</category><category>factor investing</category><category>portfolio construction</category><content:encoded><![CDATA[<p>statarb is a research library for market-neutral US equity strategies, built in layers so that every strategy family shares the same point-in-time data, cost model and evaluation code. The universe is the S&amp;P 500 as it stood on each date since 1996, rebuilt from free data. Fourteen research notes so far ask which classic ideas survive realistic costs. Twelve are pre-registered: the hypothesis, data and test are fixed in writing before the test is run.</p>
<h2 id="how-it-works">How it works <a class="header-anchor" href="#how-it-works">#</a></h2>
<ul>
<li><strong>Point-in-time data.</strong> Historical index membership, Yahoo prices, fundamentals parsed from SEC XBRL filings as of their filing dates, and factor returns from Ken French’s library. A security master resolves renamed and recycled tickers, and each manual fix is backed by evidence.</li>
<li><strong>Costs.</strong> Fees, a half-spread estimated from daily prices, square-root market impact and borrow, with trades executed on the next trading day.</li>
<li><strong>Engines.</strong> A pairs backtester (correlation, distance and cointegration selection; static and Kalman-filter hedges), cross-sectional signal books, and a cost-aware portfolio optimiser with exposure, factor, sector, turnover and liquidity constraints.</li>
<li><strong>Statistics.</strong> Newey–West t-statistics, factor regressions and bootstrap Sharpe tests, with results reported net of costs.</li>
<li><strong>A local dashboard</strong> re-prices 49 books from the saved runs, so its numbers match the notes’.</li>
</ul>
<h2 id="what-i-found">What I found <a class="header-anchor" href="#what-i-found">#</a></h2>
<div class="table-wrap"><table>
<thead>
<tr>
<th>Idea</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr>
<td>Pairs: cointegration vs correlation, 2016–26</td>
<td>Cointegration pairs lose 1.4% a year net; naive correlation pairs make 0.5% (Sharpe gap 0.85, p = 0.02). The cointegration screen passes pairs at the rate chance would</td>
</tr>
<tr>
<td>Dynamic hedge ratios</td>
<td>Slow Kalman hedges beat a frozen regression hedge, but never a simple 1:1 dollar-neutral one</td>
</tr>
<tr>
<td>Residual momentum</td>
<td>Halves momentum’s crashes (2009: −44% against −80%) but adds no alpha; neither version survives costs</td>
</tr>
<tr>
<td>Cost-aware optimisation of momentum</td>
<td>Cuts turnover from 17× to 5.7×; net Sharpe rises from −0.19 to +0.06, short of significance (p = 0.063)</td>
</tr>
<tr>
<td>Combining weak signals</td>
<td>Net Sharpe −0.23, against +0.06 for momentum alone</td>
</tr>
<tr>
<td>Quality with capped value weights</td>
<td>Five-factor alpha +4.3% a year (t = 2.4); +5.4% a year net</td>
</tr>
</tbody>
</table></div>
<p><strong>Quality is where the return is, and it is mostly a factor and mega-cap story.</strong> A quality (profitability) book held neutral to style factors and sectors lost 0.5% a year net: the quality books’ returns were factor tilts, not stock selection. The book that passed its pre-registered test is a long-short quality book with value weights, capped at 5% of a leg per company. Its alpha is measured after market, size, value, investment and momentum factors, and it earns a Sharpe ratio of 0.59 after costs. But alpha rises with concentration, from +1.7% a year with equal weights to +5.7% uncapped. Most of it came in 2021–2026 (+9.4% a year), and without Apple, Microsoft, Nvidia, Alphabet, Amazon and Meta the capped book does no better than equal weights (an exploratory check). Fifteen years of data cannot separate a lasting premium from the 2020s’ mega-cap run.</p>
<figure class="figure"><img loading="lazy" decoding="async" src="https://rasmuscodes.github.io/media/statarb/capped_quality.png" alt="Cumulative returns of quality books from equal weights to uncapped value weights, 2011–2026, and their five-factor alphas with 95% intervals" /><figcaption>Cumulative returns of quality books from equal weights to uncapped value weights, 2011–2026, and their five-factor alphas with 95% intervals</figcaption></figure>
<p><strong>A data error, caught.</strong> Share counts in some SEC filings are 1,000 to 1,000,000 times too large (77 stock-months), which made single stocks whole legs of a value-weighted book in a first run. Market caps are now screened before any value weighting, and the first run’s tables are kept for the record.</p>
<h2 id="limits">Limits <a class="header-anchor" href="#limits">#</a></h2>
<ul>
<li>Free data has a survivorship hole: delisted companies have no Yahoo prices. Coverage of index members runs from 38% in 1996 to 99% in 2026, and measured pair stability is biased upwards.</li>
<li>SEC XBRL filings start in 2009–2011, so the fundamental tests cover only about fifteen years, too few to resolve small Sharpe differences.</li>
<li>Industry codes are today’s, a slight look-ahead.</li>
<li>A CRSP adapter writes the same files, but it is untested until a WRDS connection is available.</li>
</ul>
<h2 id="how-its-built">How it’s built <a class="header-anchor" href="#how-its-built">#</a></h2>
<p>A Python package built on pandas, NumPy and cvxpy, with every raw download cached so that reruns are offline, and long runs checkpointed so they can resume. The dashboard is a standard-library server with plain HTML, CSS and its own SVG charts.</p>
]]></content:encoded></item><item><title>An options pricing and volatility lab, validated at every step</title><link>https://rasmuscodes.github.io/projects/options-lab/</link><guid isPermaLink="true">https://rasmuscodes.github.io/projects/options-lab/</guid><pubDate>Thu, 19 Nov 2026 12:00:00 +0000</pubDate><description>Pricing engines, SPX volatility surfaces and volatility forecasts on free Cboe data, each checked against independent references before the next phase starts.</description><category>options</category><category>volatility</category><category>derivatives pricing</category><category>forecasting</category><content:encoded><![CDATA[<p>options-lab is an options pricing and volatility research lab, built in phases with one rule: each phase is checked against independent references before the next one starts. Its main underlying is the S&amp;P 500 index (SPX), on free Cboe data. So far it covers pricing, implied-volatility surfaces, a historical data store and volatility forecasting. Trading strategies come next.</p>
<h2 id="how-it-works">How it works <a class="header-anchor" href="#how-it-works">#</a></h2>
<ul>
<li><strong>Pricing.</strong> Black–Scholes with Greeks to third order, an implied-volatility solver, binomial and trinomial trees, a Crank–Nicolson finite-difference solver and Monte Carlo, with American exercise and discrete dividends.</li>
<li><strong>Volatility surfaces.</strong> SVI, SSVI and extended SSVI under no-arbitrage constraints, SABR, Heston and Dupire local volatility, fitted to SPX. Plus a hybrid surface built by Andreasen–Huge volatility interpolation, which steps the forward equation from one expiry to the next and so cannot contain static arbitrage: option prices that would allow a riskless profit, such as a butterfly spread worth less than nothing.</li>
<li><strong>History.</strong> A SQLite store with provenance on every row: Cboe daily histories of SPX, the VIX family, VVIX and SKEW, plus a daily archive of SPX and SPY option chains with a fitted surface for each close.</li>
<li><strong>Forecasting.</strong> Walk-forward forecasts with monthly refits and no look-ahead, scored with QLIKE (a loss suited to variance forecasts), Diebold–Mariano tests and model confidence sets.</li>
</ul>
<h2 id="what-i-found">What I found <a class="header-anchor" href="#what-i-found">#</a></h2>
<p><strong>The hybrid surface fits more closely than SVI and has no arbitrage anywhere.</strong> On the 12 November 2026 SPX close (53 expiries, 10,735 quotes):</p>
<div class="table-wrap"><table>
<thead>
<tr>
<th>Surface</th>
<th style="text-align:right">Median error, vol points</th>
<th>Free of static arbitrage</th>
</tr>
</thead>
<tbody>
<tr>
<td>Andreasen–Huge (hybrid)</td>
<td style="text-align:right">0.11</td>
<td>Everywhere, by construction</td>
</tr>
<tr>
<td>SVI</td>
<td style="text-align:right">0.23</td>
<td>Only where quotes exist</td>
</tr>
<tr>
<td>Extended SSVI</td>
<td style="text-align:right">1.13</td>
<td>On the whole grid</td>
</tr>
</tbody>
</table></div>
<p>The hybrid surface puts 87% of quotes inside the bid-ask on the median expiry (SVI 22%), predicts held-out expiries better (0.19 against 0.27 vol points) and calibrates in 29 seconds against SVI’s 149. A check of every node probability and calendar spread at 213 maturities found none below zero. Its worst expiries are no better than SVI’s, though: the 90th-percentile slice misses by 0.30 vol points against 0.28.</p>
<p><strong>Simple forecasting models win.</strong></p>
<ul>
<li><strong>Realised volatility.</strong> For daily S&amp;P 500 forecasts from 2000 to 2026, a log-HAR model with the VIX beats every simple baseline at every horizon: its QLIKE is 7%, 25% and 22% below an exponentially weighted average’s at 1, 5 and 22 days. Gradient-boosted trees never make the confidence set. In 2000–09 they did worse than the baseline, because 2008 lay beyond anything in their training data.</li>
<li><strong>The implied side.</strong> The VIX, its term-structure slope, SKEW and VVIX all beat a random walk through mean reversion alone, and plain AR(1) and HAR models do it (22-day R² against the random walk: 13% for the VIX, 35% for the slope).</li>
<li><strong>The variance risk premium.</strong> Selling 30-day variance at the level the VIX implies paid off on 83% of days from 2000 to 2026, but no model forecasts the premium reliably better than its average.</li>
</ul>
<figure class="figure"><img loading="lazy" decoding="async" src="https://rasmuscodes.github.io/media/options-lab/qlike_by_model.png" alt="Out-of-sample QLIKE loss of thirteen volatility forecasts relative to EWMA at 1, 5 and 22 days, 2000–2026" /><figcaption>Out-of-sample QLIKE loss of thirteen volatility forecasts relative to EWMA at 1, 5 and 22 days, 2000–2026</figcaption></figure>
<p><strong>Validation found problems in the references too.</strong> In 7% of random cases, QuantLib’s Leisen–Reimer binomial engine prices American options too low, by up to 0.27, sometimes below its own European price. QuantLib’s own high-precision engine settled every disagreement in this library’s favour. And the VIX, recomputed from archived SPX quotes by Cboe’s published method, matches Cboe’s close to within 0.01 on all three days checked.</p>
<h2 id="limits">Limits <a class="header-anchor" href="#limits">#</a></h2>
<ul>
<li>The surface results rest on two SPX closes, 12 and 13 November 2026.</li>
<li>The store runs on free data only. A WRDS OptionMetrics adapter is written and tested on sample files but not connected, so option-chain history covers only the weeks since the daily archive began.</li>
<li>The forecasts are statistical results, not trading results: no strategy has been backtested yet.</li>
</ul>
<h2 id="how-its-built">How it’s built <a class="header-anchor" href="#how-its-built">#</a></h2>
<p>A Python package with NumPy, SciPy and pandas at its core. QuantLib, vollib, Let’s Be Rational, computer algebra and published examples serve as independent references in 212 validation tests. A scheduled task archives the SPX and SPY chains after each weekday close.</p>
]]></content:encoded></item><item><title>A No-Limit Hold’em solver, from heads-up flops to tournament push/fold</title><link>https://rasmuscodes.github.io/projects/nlh-solver/</link><guid isPermaLink="true">https://rasmuscodes.github.io/projects/nlh-solver/</guid><pubDate>Thu, 19 Nov 2026 12:00:00 +0000</pubDate><description>A Rust solver and browser study app for No-Limit Hold’em, for two to ten players, that labels how each answer was computed and how far it is from equilibrium.</description><category>poker</category><category>game theory</category><category>rust</category><content:encoded><![CDATA[<p>No-Limit Hold’em is the poker most people know: two hole cards each, five shared cards and bets of any size. This project is a solver and study app for it, built for real table set-ups (two to ten players, any stacks, blinds, antes, straddles, rake and tournament payouts) and built to say plainly how good each answer is. It is a companion to my <a href="https://rasmuscodes.github.io/projects/plo-solver/">Pot-Limit Omaha solver</a>.</p>
<h2 id="what-it-does-so-far">What it does so far <a class="header-anchor" href="#what-it-does-so-far">#</a></h2>
<p>The roadmap has seven phases, and five are done.</p>
<ol>
<li><strong>Core engine.</strong> Cards, ranges, four hand evaluators and a no-limit rules engine with side pots, straddles and tiered rake. The evaluators agree on all 133,784,560 seven-card hands, and every test run plays 40,000 random hands against an independent settlement check.</li>
<li><strong>Solver.</strong> CFR (counterfactual regret minimisation: the strategy plays against itself many times and shifts towards the moves it regrets not making), in its Discounted, CFR+ and Linear forms. It reproduces the known values of two toy poker games and measures exploitability exactly: how much a perfect opponent could win against the strategy, as a share of the pot.</li>
<li><strong>Browser app.</strong> A local server and a React interface with range, board and bet-size editors, a convergence chart and a strategy explorer. The acceptance test was a 3-bet-pot flop of 2.26 million nodes, solved from the browser to 0.498% of the pot, then explored, saved and reopened.</li>
<li><strong>Advanced solving.</strong> Node locking (fixing one player’s play at chosen spots and solving the rest against it), exploit reports, preflop all-in charts, three-way turn and river solves, bucketed three-way flops and whole-hand preflop blueprints for two to six players. Its heads-up push/fold charts match a published chart on 162 values to within 0.10 big blinds.</li>
<li><strong>Tournaments.</strong> ICM (the Independent Chip Model, which turns chip stacks into shares of the prize pool), bubble factors, presets for sit &amp; go, final-table, satellite and Spin formats, a labelled bounty model, and push/fold solves for a whole table of two to ten players.</li>
</ol>
<h2 id="checking-the-answers">Checking the answers <a class="header-anchor" href="#checking-the-answers">#</a></h2>
<p>Every fast path has a slow reference it is tested against, and the reference is checked against an independent Python implementation. ICM equities match 62 reference cases to within one part in a hundred billion.</p>
<p>Push/fold at a full table was checked against a simulation that deals every hand from one deck. Every player’s value is now within 0.0062 big blinds a hand of the dealt game, on 4 to 10 million simulated hands per table. The first version was off by up to 0.038 big blinds, because it ignored that folded hands are weaker than random.</p>
<p>Every result also says how it was computed. Heads-up solves report exploitability. With three or more players an equilibrium guarantees nothing, so those results report NashConv (the total that all players could gain by switching to their best responses) under a “multiway CFR approximation” label. Blueprints are marked as approximations of a simplified game, with no exploitability figure. Nothing is called GTO (game-theory optimal) unless the method supports it.</p>
<h2 id="limits">Limits <a class="header-anchor" href="#limits">#</a></h2>
<ul>
<li><strong>Three-way flops are still rough.</strong> Their measured NashConv is about 10% of the pot on a small study flop after 37,632 sampled runouts.</li>
<li><strong>Push/fold allows at most three players all in</strong>, and folded cards are not yet removed from the deck for the board. That leaves the blinds about 0.005 big blinds a hand off at six to ten players.</li>
<li><strong>ICM looks at one hand at a time</strong> and covers push/fold only. The raise trees and the postflop solver still count chips.</li>
<li><strong>Saved full flops are big:</strong> 816 MB for one single-raised-pot flop. Timings come from a busy machine and are pessimistic.</li>
</ul>
<h2 id="how-its-built">How it’s built <a class="header-anchor" href="#how-its-built">#</a></h2>
<p>A Rust workspace of 11 crates, from cards and rules through the solvers to a command-line tool and a local HTTP server. The only outside Rust dependencies are serde, serde_json and rayon. The browser app is React and TypeScript. All randomness flows from explicit seeds, so results do not depend on thread scheduling, and 249 automated tests pass.</p>
<p>Next on the roadmap: hand-history import and review, and special games such as bomb pots, double-board pots and the 7-2 game.</p>
]]></content:encoded></item><item><title>A market simulator in Rust, checked order by order against real data</title><link>https://rasmuscodes.github.io/projects/hft-sim/</link><guid isPermaLink="true">https://rasmuscodes.github.io/projects/hft-sim/</guid><pubDate>Thu, 19 Nov 2026 12:00:00 +0000</pubDate><description>A deterministic exchange, a latency-aware simulator and a market-making ladder, with a fill model tested on real Bitstamp and Nasdaq order data.</description><category>market microstructure</category><category>market making</category><category>simulation</category><category>rust</category><content:encoded><![CDATA[<p>hft-sim is a research platform for market microstructure: how orders become trades and prices. It has a deterministic exchange, a simulator in which every message takes time to arrive, trading agents and a ladder of market-making strategies. I wanted to know how market makers fare against latency, informed traders and competition, and whether a backtest’s rule for when a resting order fills survives real exchange data.</p>
<h2 id="how-it-works">How it works <a class="header-anchor" href="#how-it-works">#</a></h2>
<ul>
<li><strong>The exchange</strong> matches orders by price-time priority: best price first, then first come, first served.</li>
<li><strong>The simulator</strong> times every hop between a trader and the exchange, so traders see only a delayed copy of the book. Runs are bit-reproducible from one seed.</li>
<li><strong>A background market</strong> of noise traders, value investors and split-up large orders is calibrated to five statistical regularities of real markets.</li>
<li><strong>The market makers</strong> form a ten-step ladder, from a fixed spread to the Avellaneda–Stoikov and Guéant–Lehalle–Fernandez-Tapia models, with formulas transcribed from the papers and checked numerically.</li>
</ul>
<h2 id="what-the-simulator-showed">What the simulator showed <a class="header-anchor" href="#what-the-simulator-showed">#</a></h2>
<p>Eight research questions, each on two backgrounds with 8 seeds and 95% intervals, about this simulated market only.</p>
<ul>
<li><strong>More inventory aversion paid.</strong> Raising a market maker’s risk aversion from 3.5 to 14 added $9.2 per two-minute window [5.9, 12.5] with less inventory. The gain came from less adverse selection (trading against flow that knows where the price is going), even without informed traders: the background’s split orders are persistent.</li>
<li><strong>Queue position dominates fills.</strong> A resting order at the front of the queue filled about 90% of the time; behind 500 shares, about 10%.</li>
<li><strong>Speed mattered little here.</strong> A remote maker sent three times as many cancels too late (8% against 2–3%) but lost little profit: it had no news to race on.</li>
<li><strong>The maker profited almost everywhere</strong>, even against 60 informed traders. That is a property of the simulator, and it is why nothing here is a profitability claim.</li>
</ul>
<h2 id="checking-the-fill-model-on-real-data">Checking the fill model on real data <a class="header-anchor" href="#checking-the-fill-model-on-real-data">#</a></h2>
<p>Each real order was replayed leave-one-out: treated as hypothetical, run through the stream without itself, and its modelled fills compared with what really happened.</p>
<div class="table-wrap"><table>
<thead>
<tr>
<th>Data</th>
<th>Check</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bitstamp BTC/USD, 19 minutes, 365,180 order events</td>
<td>Rebuilt book against the exchange’s own snapshots</td>
<td>1,136 of 1,136 reproduced</td>
</tr>
<tr>
<td>172,862 resting Bitstamp orders</td>
<td>Fill model, four variants</td>
<td>No false, early or oversized fill</td>
</tr>
<tr>
<td>The same orders, best variant</td>
<td>Real fills found at the right millisecond</td>
<td>292 of 298, 99.6% of volume</td>
</tr>
<tr>
<td>Nasdaq BX ITCH day (30 Dec 2019), 801,154 orders</td>
<td>Fill model</td>
<td>No false, early or oversized fill</td>
</tr>
</tbody>
</table></div>
<p>The best variant uses Bitstamp’s published taker orders (the incoming orders that trade against resting ones) and rebuilds history as if each order had never existed. Without takers, as on Nasdaq’s feed, the conservative rules give a lower bound: a third of Bitstamp’s fills on time, and 93% of BX volume eventually. The BX day’s 29.2 million messages also pass every book-consistency check.</p>
<p>The checks exposed three optimistic rules in my model, each now fixed. On BX, 0.2% of executions looked like queue jumping; every one was an order the exchange ranks at a better price than it displays (its Price to Comply rule).</p>
<h2 id="limits">Limits <a class="header-anchor" href="#limits">#</a></h2>
<ul>
<li>The default background makes one-second returns mean-revert, so every study also runs on a second, zero-intelligence background.</li>
<li>The real data is one 19-minute crypto window and one day on a small Nasdaq venue. The LOBSTER adapter is tested only on simulated files, because LOBSTER’s samples now need an academic application.</li>
<li>Replay cannot show how the market would have reacted to an extra order.</li>
</ul>
<h2 id="how-its-built">How it’s built <a class="header-anchor" href="#how-its-built">#</a></h2>
<p>A Rust workspace whose core crates have no external dependencies and no unsafe code, plus a Python layer for scenario grids with optional PyO3 bindings that export runs to Parquet. The 213 Rust and 27 Python tests include differential fuzzing against a naive reference exchange (about 18 million commands) and mutation testing: of 132 deliberately planted bugs, 130 were caught and the other two provably cannot change any output. The engine handles about 8.6 million messages a second with 1,000 resting orders on a laptop.</p>
]]></content:encoded></item><item><title>A game-theory solver for six-handed Pot-Limit Omaha</title><link>https://rasmuscodes.github.io/projects/plo-solver/</link><guid isPermaLink="true">https://rasmuscodes.github.io/projects/plo-solver/</guid><pubDate>Thu, 19 Nov 2026 12:00:00 +0000</pubDate><description>A Rust solver and study app for 6-max PLO, built milestone by milestone, from an exact rules engine to a library of exactly solved flops that grows in the background.</description><category>poker</category><category>game theory</category><category>rust</category><content:encoded><![CDATA[<p>Pot-Limit Omaha deals four hole cards instead of hold’em’s two, so the game is far larger: there are 16,432 strategically different starting hands. This project is a 6-max PLO analysis platform, built toward a mathematically sound game-theoretic solver with a modern study interface.</p>
<h2 id="what-it-does-so-far">What it does so far <a class="header-anchor" href="#what-it-does-so-far">#</a></h2>
<ul>
<li><strong>Foundation (M1-M2).</strong> An exact rules engine, a table-driven Omaha hand evaluator, exact and Monte Carlo equity, and the solver: vector-form CFR (counterfactual regret minimisation), CFR+ and Discounted CFR with exact card removal, validated on Kuhn poker and Leduc hold’em, where the answers are known. Each solve reports its exploitability: how much a perfect opponent could win against it.</li>
<li><strong>Postflop (M3-M4, M7-M8).</strong> Exact heads-up turns, node locking (fixing one player’s play at chosen spots), off-tree bet sizes, abstracted heads-up flops measured in the real game, and multiway river and turn spots.</li>
<li><strong>Preflop (M5-M6, M14).</strong> Blueprints by Monte Carlo CFR over whole hands, covering all 16,432 preflop hand classes: heads-up, a six-handed blueprint on a restricted tree, and tables of three to five players.</li>
<li><strong>Hand-history analysis (M7, M9, M14).</strong> PokerStars-style hand histories import into the app. A file of up to 5,000 hands is checked against the blueprints preflop, and every flop the hero played can be solved in a batch, with the EV given up at each decision.</li>
<li><strong>Tournaments (M12-M13).</strong> The big-blind ante, exact ICM (the Independent Chip Model, which turns chip stacks into prize equity), per-seat stacks, and blueprints and solves with ICM payoffs.</li>
<li><strong>A pre-solved library (M10-M15).</strong> 83 standard spots, from heads-up and 6-max cash to tournament bubbles and final tables, each solved on a set of representative flops. Library flops are solved exactly (the full game, every turn and river card) to within 0.5% of the pot, and stored at the flop level: about 0.2 MB instead of 500 MB. Any turn you pick is solved again exactly in seconds.</li>
<li><strong>Speed and scale (M16-M17).</strong> Exact solves are 1.33 times faster after the evaluator work, and Discounted CFR with restarts needs 12-20% fewer iterations to reach 0.5% of the pot. Regrets and strategy sums are now stored in 16 bits, which halves the RAM a deep heads-up flop needs, from 4.66 GB to 2.33 GB, with the same convergence. A background builder adds exact flops one at a time, pausing whenever I solve something myself: over 2,100 since 15 November.</li>
<li><strong>A second bet menu (M17).</strong> A 33% flop bet beside the pot-sized one. All of the first 20 flops checked reached 0.5% of the pot, and the small bet was worth 0.15% (heads-up) to 0.38% (6-max) of the pot to the raiser on average.</li>
</ul>
<h2 id="how-its-built">How it’s built <a class="header-anchor" href="#how-its-built">#</a></h2>
<p>A Rust workspace of nine crates, from cards, pot-limit rules and equity through game trees, the CFR and Monte Carlo CFR solvers and a compact solution store, to a command-line tool and a local HTTP server. The server’s JSON API drives a React and TypeScript study interface. An independent Python reference implementation supplies test vectors. Every milestone ends with a report of what was built, measured and tested, and what is still missing.</p>
<h2 id="honest-limits">Honest limits <a class="header-anchor" href="#honest-limits">#</a></h2>
<ul>
<li>With three or more players, CFR carries no Nash guarantee, so multiway results are labelled that way. The distance from equilibrium (NashConv) is measured exactly for two or three players with modest ranges on the river and turn, but not on multiway flops, which bucket later streets.</li>
<li>Blueprints are approximations of an abstracted game. Their exploitability in the real game can’t be measured here.</li>
<li>Exact library flops use the blueprint’s ranges, sampled to 1,000 hands per side, and turns and rivers keep a single pot-sized bet. Two sizes there would need 5-12 GB per flop, more than the laptop spares.</li>
<li>Each spot covers 30 or 100 representative flops, weighted by the share of all 22,100 flops each stands for. There are 1,755 strategically different flops, so coverage is the largest gap.</li>
</ul>
<h2 id="next">Next <a class="header-anchor" href="#next">#</a></h2>
<p>Let the builder finish rolling out the second bet menu, then compare the main lines’ 30 flops the same way. A third flop size (33%, 66% or pot) follows if those flops support it.</p>
]]></content:encoded></item><item><title>A Figgie bot that counts cards and reads the market</title><link>https://rasmuscodes.github.io/projects/figgie-bot/</link><guid isPermaLink="true">https://rasmuscodes.github.io/projects/figgie-bot/</guid><pubDate>Thu, 19 Nov 2026 12:00:00 +0000</pubDate><description>An exact Bayesian card counter that trades Jane Street’s card game, live on figgie.com and in a Python simulator.</description><category>trading</category><category>game theory</category><category>bots</category><content:encoded><![CDATA[<p>Figgie is Jane Street’s card-trading game. Four players each get ten cards from a 40-card deck in which one suit is secretly the goal, then trade with each other for four minutes in an open market. Every goal card pays $10 at the bell, and the rest of the pot goes to whoever holds the most of them. This bot plays it, live on <a href="http://figgie.com" target="_blank" rel="noopener">figgie.com</a> against the site’s Hard bots and in a simulator against opponents written to beat it.</p>
<p>The <a href="https://rasmuscodes.github.io/essays/teaching-a-bot-to-trade-figgie/">full write-up</a> tells the story version by version, including the ideas that lost money.</p>
<h2 id="how-it-thinks">How it thinks <a class="header-anchor" href="#how-it-thinks">#</a></h2>
<ol>
<li><strong>It counts cards exactly.</strong> There are only 12 possible decks, so it keeps the probability of each. Its own hand is the first evidence, and the tape adds hard facts: nobody can sell a card they don’t hold.</li>
<li><strong>It reads the market.</strong> High bids are votes for a suit. The cleanest tell is player by player: every Hard bot bids the goal suit up at some point, while a dead suit draws a big bid from only one of them. A bid counts only once it has stood on the book in two different seconds, so a flashed bid can’t steer it.</li>
<li><strong>It prices adverse selection.</strong> Early in a round, whoever buys from it probably knows more, so its offers are priced as if they do, and it never sells a card for less than the option of holding it.</li>
<li><strong>It values the majority bonus.</strong> Once it holds half the goal suit, the next card decides between a tie and a win, and it pays up for it.</li>
<li><strong>It learns from the table.</strong> An online Bayesian logistic regression learns which cheap offers resell within seconds, from every offer on the tape, and at each bell it updates how far to trust each market signal at that table.</li>
</ol>
<h2 id="results">Results <a class="header-anchor" href="#results">#</a></h2>
<p>Across 142 live rounds it made $6,958 in play money. Every live test since v3 has been profitable, and over the last 41 rounds (v11 to v13.3) it averaged $81 a round, ±$18 at 95% confidence, with 34 of 41 rounds in profit. The newest version opens its own tables and runs unattended: its first long session made $810 over 11 rounds at three tables.</p>
<div class="table-wrap"><table>
<thead>
<tr>
<th>Version</th>
<th style="text-align:right">Live rounds</th>
<th style="text-align:right">Per round</th>
<th style="text-align:right">±95%</th>
<th>What changed</th>
</tr>
</thead>
<tbody>
<tr>
<td>v1</td>
<td style="text-align:right">9</td>
<td style="text-align:right">−$29.0</td>
<td style="text-align:right">±35</td>
<td>Exact card counting, naive market-making</td>
</tr>
<tr>
<td>v3</td>
<td style="text-align:right">10</td>
<td style="text-align:right">+$42.3</td>
<td style="text-align:right">±35</td>
<td>Won’t sell a card before the market reveals the goal</td>
</tr>
<tr>
<td>v8</td>
<td style="text-align:right">10</td>
<td style="text-align:right">+$33.5</td>
<td style="text-align:right">±34</td>
<td>Weighs whether every opponent bid a suit up</td>
</tr>
<tr>
<td>v10</td>
<td style="text-align:right">10</td>
<td style="text-align:right">+$60.3</td>
<td style="text-align:right">±34</td>
<td>Buys cheap dead cards and resells them, with a kill switch</td>
</tr>
<tr>
<td>v12</td>
<td style="text-align:right">10</td>
<td style="text-align:right">+$79.9</td>
<td style="text-align:right">±34</td>
<td>Learns which cheap offers resell, from the tape</td>
</tr>
<tr>
<td>v13</td>
<td style="text-align:right">10</td>
<td style="text-align:right">+$98.9</td>
<td style="text-align:right">±32</td>
<td>Learns which market signals to trust at a table</td>
</tr>
<tr>
<td>v13.3</td>
<td style="text-align:right">11</td>
<td style="text-align:right">+$73.6</td>
<td style="text-align:right">±37</td>
<td>Reacts to each quote at once; runs unattended</td>
</tr>
</tbody>
</table></div>
<p>Ten rounds is a small sample: most single steps between versions are inside the noise, so decisions were made on paired simulations (the same deals for both versions) and replays of logged rounds, with live tests as the final check.</p>
<h2 id="what-it-still-gets-wrong">What it still gets wrong <a class="header-anchor" href="#what-it-still-gets-wrong">#</a></h2>
<ul>
<li><strong>Colluders who know the goal beat it.</strong> Three of them take about $60 a round in the simulator whatever it believes, because they sell it dead cards and buy its goal cards.</li>
<li><strong>Its opponents are bots, not people.</strong> <a href="http://figgie.com" target="_blank" rel="noopener">figgie.com</a>’s bots are predictable in ways people aren’t.</li>
<li><strong>A better forecast didn’t pay.</strong> A model that read each opponent’s tells put more probability on the true goal and still lost $2 a round in simulation, because the bonus goes to whoever commits.</li>
</ul>
<h2 id="how-its-built">How it’s built <a class="header-anchor" href="#how-its-built">#</a></h2>
<p>The game engine, the probability model, a simulator with fifteen kinds of opponents and the analysis tools are about 4,400 lines of standard-library Python. A test bench, the arena, plays every change in paired sessions at 21 tables with separate seeds for tuning, choosing and reporting. The live bot is a 2,900-line userscript that carries a line-for-line JavaScript port into the page, and a harness checks that both versions compute the same probabilities and send the same orders.</p>
<p>It only trades at private tables where every other seat is a <a href="http://figgie.com" target="_blank" rel="noopener">figgie.com</a> bot, for play money, uses only what a player can see and places at most four orders a second.</p>
]]></content:encoded></item><item><title>A deal tracker for Coherent and AAOI that quotes every claim verbatim</title><link>https://rasmuscodes.github.io/projects/optical-intel/</link><guid isPermaLink="true">https://rasmuscodes.github.io/projects/optical-intel/</guid><pubDate>Thu, 19 Nov 2026 12:00:00 +0000</pubDate><description>A daily pipeline over filings, newsrooms, trade press and Chinese exchange disclosures, with a hand-curated layer of deals re-checked against its sources on every run.</description><category>alternative data</category><category>optical</category><category>text mining</category><category>data engineering</category><content:encoded><![CDATA[<p>This is a commercial-intelligence database for two US makers of optical components for data centres: Coherent and Applied Optoelectronics (AAOI). It collects primary sources about them and their customers, suppliers and competitors, pulls out commercial events such as contracts, design wins and capacity changes, and writes a daily and a weekly report. The question behind it: how much can be established about these companies’ deals from public documents alone, with every claim tied to its evidence?</p>
<h2 id="how-it-works">How it works <a class="header-anchor" href="#how-it-works">#</a></h2>
<ul>
<li><strong>Collection.</strong> SEC filings for both companies since 2016 and for 14 peers and DSP-chip vendors since 2021, plus SEC full-text search, XBRL financial data, company newsrooms, trade-press feeds, Texas construction-project filings for new fabs, federal awards, patents and the exchange disclosures of nine Chinese competitors. Every request checks robots.txt and per-host rate limits, and every raw response is stored with a checksum. Sources that block scripts or rule out automated access, such as the big newswires, LinkedIn and paywalled research, are listed with the reason and never requested.</li>
<li><strong>Extraction.</strong> A gazetteer recognises companies, technologies and products, with date windows and guards: “coherent optics” is not the company, and Finisar folds into Coherent after the merger. Twenty sentence-level rules tag events. Boilerplate and risk-factor lists are filtered out, and a sentence already seen in an earlier document counts for less, so a press release mirrored in an 8-K is not news twice.</li>
<li><strong>Scoring.</strong> Each event gets a 0–100 materiality score from the source’s tier, the type of event, the named counterparty and any stated dollar value relative to the company’s revenue. It is a ranking, not a forecast.</li>
<li><strong>Curated layer.</strong> Deals, relationships, facilities, capacity statements, launches and industry developments are written by hand as records with verbatim quotes. Every quote is checked against the stored source text on each run, and any change creates a new version. An undisclosed customer is never named as fact: an identification is a separate record marked “inferred”, with its corroboration and a confidence level.</li>
<li><strong>Monitoring.</strong> A scheduled job runs every morning. It collects new documents, re-verifies the curated layer, writes the reports and raises alerts for material items first seen since the previous run.</li>
</ul>
<h2 id="what-it-found">What it found <a class="header-anchor" href="#what-it-found">#</a></h2>
<p>The first build, on 12 November 2026, held 13,297 documents from 20 sources and 149 curated records, all of which passed verification. Some of what it documented:</p>
<ul>
<li><strong>One customer, two suppliers, one day.</strong> NVIDIA signed near-identical multi-year purchase agreements with Coherent and Lumentum on the same day in March 2026, each with a $2bn investment. Coherent rose 15.4% against a flat S&amp;P 500 that day, so the deal was not expected.</li>
<li><strong>An undisclosed customer, by arithmetic.</strong> Revenue linked to Amazon’s warrant was 26.4% of AAOI’s revenue in the first nine months of 2026, matching the 26% the 10-Q gives for AAOI’s second-largest customer. That makes Amazon very likely customer number two. It is an inference from matching numbers and is stored as one.</li>
<li><strong>A disclosure in someone else’s filing.</strong> Coherent’s prepayment for indium-phosphide substrate capacity appears in its supplier AXT’s filing, not in Coherent’s own.</li>
<li><strong>Filings that disagree with themselves.</strong> Two of AAOI’s 10-Ks each give two different figures for Microsoft’s share of revenue; the 2021 report says both 14.1% and 25.6%. The customer-concentration parser reconciles these sentences across filings and flags the conflict instead of silently picking one.</li>
</ul>
<h2 id="limits">Limits <a class="header-anchor" href="#limits">#</a></h2>
<ul>
<li>The rule-based extraction aims for recall, so an event needs reading before it is relied on.</li>
<li>No consensus estimates are connected. The stock’s reaction around a disclosure stands in for “was it expected”, and that reaction mixes in everything else released that day.</li>
<li>Coherent does not file its customer or supply agreements as exhibits, so their terms are known only from press releases and 10-K summaries.</li>
<li>History is uneven. Coherent’s newsroom sitemap starts in December 2020, and most trade press is complete only from the start of collection.</li>
</ul>
<h2 id="how-its-built">How it’s built <a class="header-anchor" href="#how-its-built">#</a></h2>
<p>Python with SQLite, using WAL mode and FTS5 full-text search with BM25 ranking, plus requests, BeautifulSoup and pypdf for retrieval and text extraction. A command-line tool covers search, events, deals, company profiles, customer-concentration history and announcement-day returns, and exports plain CSV and Excel files. Twenty unit tests run without network access.</p>
]]></content:encoded></item></channel></rss>
