Quant models for trading

Dealer gamma on the SPX chain, a gamma scalping run with real fills, Almgren-Chriss execution on ADBE and Avellaneda-Stoikov market making on SPY, from real intraday bars, and LLM agents trading live on paper accounts. Five models, each with its code and its data.

Five models from a trading desk

Each model answers a question a desk asks every day. Where will dealer hedging push the index? Is an option paying for its own decay? How fast should a large order go? Where should a market maker quote with inventory on the book? And can a language model place the trade?

Every code block below runs as pasted. Raw market data is licensed and stays out; the repository on GitHub holds the tables derived from it, so each block reads exactly what produced the numbers on this page. Only the market making block downloads data, its SPY session from Yahoo Finance. No API key and no subscription.

Read the limitations before quoting any number here. GEX rests on an assumption about the dealers' side, market making fills are simulated, and two trading sessions are a test of the method, far too few to judge a strategy.

All the code is on GitHub

Five models in one script, the data files, every chart and the output it prints, ready to clone and run.

Watch the videos: trading automation and LLMs

Both builds run live on the channel. A Python bot trades an SPX straddle hedged with MES futures on Interactive Brokers, the same afternoon as section 2. Vibe-Trading puts AI agents on DeepSeek and Claude through setup, a backtest and an investment committee. Trading automation and language models inside the trading loop are what the channel covers, one tested build per video.

Gamma Scalping Trading Bot in Python: Live on Interactive Brokers. Write up: gamma scalping bot.

Open Source Vibe Trading on DeepSeek and Claude: Setup, Backtest and Committee. Write up: Vibe-Trading test.

Subscribe on YouTube

On X

Follow me on X, my models are there

I post the models as I build them, the changes I make to them, and the results that did not work. Shorter than these write ups, and there are a lot more of them.

Follow me on X
Newsletter

Get exclusive models, prompts and code

One short email when there's something new. finance models, code walkthroughs, agentic prompts. No spam.

Built with
Anthropic Claude Python R ChatGPT GitHub Jupyter Excel PowerPoint VS Code SQL MATLAB

All the code is on GitHub

Each section below explains one model, where it is used, its code and its charts. Same code sits in one file in the repository, with the data and the output it prints.

1. GEX, dealer gamma exposure

Options dealers hedge what they sell. A dealer long gamma has to sell futures as the index rises and buy as it falls, which damps the move. A dealer short gamma trades with the move and makes it bigger. GEX adds that hedging up across the whole SPX chain: gamma times open interest times 100, times spot squared, times 1%, gives the dollars to re-hedge for a 1% move.

Nobody outside the dealers sees their book, so the usual convention has customers buying puts for protection and selling calls for income, which leaves dealers long the calls and short the puts. Repricing the chain at other spot levels finds the gamma flip, where net gamma changes sign. Strikes with the largest net call and put gamma are the call wall and the put wall.

Index and same day options traders read the flip as the line between a market that mean reverts and one that trends, and vol traders use the sign to judge whether realized vol should run under or over implied. SqueezeMetrics publishes a daily GEX series, and Baltussen, Da, Lammers and Martens (2021) tie the momentum of index futures into the close to days when dealers are short gamma.

Net dealer gamma by strike on the SPX chain, with spot, the gamma flip and the walls
Net dealer gamma by strike at the close of 9 Sep 2026, 19,859 contracts on 48 expiries. Blue strikes are call heavy, orange put heavy.

Cboe's chain stays out of the repository. Code below carries the formula and reads the tables it produced on the saved chain: dealer gamma by strike, by days to expiry, and with the whole book repriced at every SPX level.

Dealer gamma, the flip and the walls, from the chain's tables

import numpy as np, pandas as pd
from scipy.stats import norm

def dealer_gex(S, K, T, iv, oi, is_call, r=0.04):
    """Dollars of SPX dealers re-hedge per 1% move, if they are long the calls and short the puts.
    Summed over every contract of the SPX chain, it gives the tables read below."""
    T = np.maximum(T, 4 / (365 * 24))                    # four hour floor, for options expiring today
    d1 = (np.log(S / K) + (r + iv ** 2 / 2) * T) / (iv * np.sqrt(T))
    gamma = norm.pdf(d1) / (S * iv * np.sqrt(T))
    return np.where(is_call, 1, -1) * gamma * oi * 100 * S ** 2 * 0.01

DATA = "https://raw.githubusercontent.com/davidalmeida90/quant-models/main/trading-models/data/"
book = pd.read_json(DATA + "gex_summary.json", typ="series")              # SPX chain, close of 9 Sep 2026
by_strike = pd.read_csv(DATA + "gex_by_strike.csv", index_col="strike")    # $bn per 1% move at the close
by_expiry = pd.read_csv(DATA + "gex_by_expiry.csv", index_col="days_to_expiry")
profile = pd.read_csv(DATA + "gex_profile.csv")                            # net $bn if SPX sat at each level
spot, walls, net = book.spot, by_strike.net_bn, profile.net_bn.values

i = np.where(np.diff(np.sign(net)))[0][0]                                  # net gamma changes sign here
flip = profile.spx[i] - net[i] * (profile.spx[i + 1] - profile.spx[i]) / (net[i + 1] - net[i])

example = dealer_gex(spot, 7700, 30 / 365, 0.13, 10_000, True) / 1e9       # a made-up call, to show the formula
print(f"one 7,700 call, 30 days, 13% vol, 10,000 contracts open: {example:+.2f}bn per 1% move")
print(f"{book.contracts:,} contracts on {book.expiries} expiries, net dealer gamma {book.net_bn:+.1f}bn per 1% move")
print(f"calls {book.calls_bn:+.1f}bn, puts {book.puts_bn:+.1f}bn, expiring within a day {by_expiry.net_bn['0-1d']:+.1f}bn")
print(f"gamma flip {flip:,.0f}, spot {spot:,.0f}, {spot / flip - 1:+.1%} from it")
print(f"call wall {walls.idxmax():,.0f} ({walls.max():+.1f}bn), put wall {walls.idxmin():,.0f} ({walls.min():+.1f}bn)")
SPX chain at the close of 9 Sep 2026, Cboe delayed quotes, 21,974,909 contracts open
MeasureValue
Spot7,637
Net dealer gamma, per 1% move-$40.7bn
Calls, dealers long+$293.1bn
Puts, dealers short-$333.8bn
Expiring within a day-$31.8bn
Gamma flip7,667
Call wall7,800, +$5.3bn
Put wall7,500, -$9.0bn

With spot 0.4% below the flip, dealers were short $41bn of gamma per 1% move: a 1% drop has them selling about that much SPX exposure and a 1% rally has them buying, so their hedging adds to the move. $32bn of it sat in options expiring within a day, a part of the book that is gone by the next session. Only options beyond 90 days leaned long, +$27bn.

A rally of 0.4% would cross the flip, and at the call wall of 7,800 the same book turns to +$157bn, long enough to damp the move. At the put wall of 7,500 it reads -$99bn.

Net dealer gamma across SPX levels with the gamma flip marked
Same book repriced at every SPX level, open interest and implied vols held fixed. Net gamma changes sign at the flip.

2. Gamma scalping

Buy an at the money straddle and the position is long gamma: its delta grows as the index rises and shrinks as it falls. Hedging that delta back to zero means selling futures after a rise and buying after a fall, so every swing locks in a small gain. Theta is the rent. Each day the straddle loses value, and the hedges only pay for it if the index moves more than the implied vol priced in.

Breakeven daily move is implied vol times spot over the square root of 252. Carr and Madan (1998) showed that a delta hedged option earns the gap between realized and implied variance, weighted by its gamma, so a gamma scalper is long realized vol and short implied. Volatility funds and options market makers run this trade every day, and event traders buy the straddle before a release to scalp the move that follows.

On 2 Nov 2026 a Python engine bought 1 SPX straddle at 7,615, expiring 30 Nov, on an Interactive Brokers paper account, and hedged with micro E-mini futures (MES, $5 a point) whenever net delta left a band of 1 MES. Fills below are the real ones.

S&P 500 every minute of the run with the hedge band and the four MES trades
S&P 500 every minute of the run. Shaded: the band where net delta stays within 1 MES. Each dot is a fill on the paper account.

Fills, implied vol from the straddle, and where the dollars came from

import numpy as np, pandas as pd
from scipy.stats import norm
from scipy.optimize import brentq

DATA = "https://raw.githubusercontent.com/davidalmeida90/quant-models/main/trading-models/data/"
fills = pd.read_csv(DATA + "gamma_scalping_fills_2026-11-02.csv", parse_dates=["time_et"])
path = pd.read_csv(DATA + "gamma_scalping_path_2026-11-02.csv")      # SPX every minute of the run
K, expiry, r = 7615, pd.Timestamp("2026-11-30 16:00"), 0.037

def black(F, T, vol):
    """Black 76 straddle on the forward: call plus put, same strike."""
    d1 = (np.log(F / K) + vol ** 2 * T / 2) / (vol * np.sqrt(T))
    d2 = d1 - vol * np.sqrt(T)
    return np.exp(-r * T) * (F * norm.cdf(d1) - K * norm.cdf(d2) + K * norm.cdf(-d2) - F * norm.cdf(-d1))

def implied(call, put, when):
    T = (expiry - when).total_seconds() / (365 * 86400)
    F = K + (call - put) * np.exp(r * T)                                # put call parity gives the forward
    return F, T, brentq(lambda v: black(F, T, v) - call - put, 0.01, 1.0)

leg = lambda inst, kind: fills[(fills.instrument == inst) & (fills.kind == kind)].iloc[0]
c0, p0, c1, p1 = leg("call", "entry"), leg("put", "entry"), leg("call", "exit"), leg("put", "exit")
F0, T0, iv0 = implied(c0.price, p0.price, c0.time_et)
F1, T1, iv1 = implied(c1.price, p1.price, p1.time_et)

d1 = (np.log(F0 / K) + iv0 ** 2 * T0 / 2) / (iv0 * np.sqrt(T0))
gamma = 2 * np.exp(-r * T0) * norm.pdf(d1) / (F0 * iv0 * np.sqrt(T0))   # straddle gamma per SPX point
theta = 0.5 * gamma * F0 ** 2 * iv0 ** 2 / 252 * 100                    # dollars lost per trading day
breakeven = iv0 * c0.spx / np.sqrt(252)                                 # daily move that pays it back
realized = np.diff(np.log(path.spx)).std() * np.sqrt(252 * 390)         # 1 minute returns

straddle = (c1.price + p1.price - c0.price - p0.price) * 100            # SPX multiplier 100
mes = fills[fills.instrument == "MES"]
hedges = (np.where(mes.side == "SELL", 1, -1) * mes.price).sum() * 5    # MES multiplier 5
fees = fills.commission.sum()
vol_part = (black(F1, T1, iv1) - black(F1, T1, iv0)) * 100              # exit, repriced at the entry vol

print(f"bought the {K} straddle for {c0.price + p0.price:.2f} points, implied vol {iv0:.1%}")
print(f"theta {-theta:,.0f} dollars a trading day, breakeven move {breakeven:.0f} points "
      f"({breakeven / c0.spx:.2%}), realized vol over the run {realized:.1%}")
print(f"straddle {straddle:+,.2f}, MES hedges {hedges:+,.2f}, commissions {-fees:+,.2f}, "
      f"total {straddle + hedges - fees:+,.2f} dollars")
print(f"implied vol {iv0:.2%} to {iv1:.2%}: worth {vol_part:+,.0f}, "
      f"everything else {straddle + hedges - fees - vol_part:+,.0f} dollars")
1 SPX straddle, 7,615 strike, 30 Nov 2026 expiry, hedged with MES
LegBoughtSoldP&L
Call 7,615136.60120.90-$1,570.00
Put 7,615117.00140.40+$2,340.00
MES hedges4 trades+$138.75
Commissions8 orders-$8.96
Total+$899.79

Straddle cost 253.60 points at 15.0% implied vol, a theta of $650 a trading day and a breakeven move of 72 points (0.95%) a day. Realized vol over the run was 10.9%, well under the vol priced in, so gamma on its own lost to theta.

Profit came from vol. As the S&P fell, 59 points at the low, implied vol rose from 15.03% to 15.56%. Repricing the exit with the entry vol puts that move at +$886. Everything else (gamma against theta, the delta left between hedges, commissions) nets to +$14. One afternoon says nothing about an edge; it shows every moving part with real fills.

Waterfall of the gamma scalping P&L: implied vol, the rest of the straddle, hedges, commissions
Same total, split into the implied vol move and everything else.

3. Almgren-Chriss optimal execution

A large order moves the price against itself. Sell it all at once and impact eats the proceeds; spread it over the day and the price can drift away in the meantime. Almgren and Chriss (2000) wrote the trade-off as one objective, expected cost plus lambda times its variance, and solved for the schedule. Lambda at zero gives the cheapest schedule on average, and every higher lambda sells earlier to cut the risk.

min  E[cost] + λ · Var[cost]

Implementation shortfall algorithms at brokers descend from it: the portfolio manager picks the urgency, which is lambda, the algorithm sets the schedule, and transaction cost analysis grades the fills against the arrival price.

Here impact in each 5 minute bucket is inversely proportional to that bucket's average volume, so selling into the opening and closing rush costs less, and with no risk aversion the solution is exactly VWAP. Volume and volatility by bucket come from 500 sessions of ADBE 5 minute bars, 12 Nov 2024 to 17 Nov 2026; only the averages are shipped. Impact follows Almgren, Thum, Hauptmann and Li (2005), who measured on real orders that a one day VWAP costs 0.142 sigma times the participation rate to the power 0.6, and the linear model is matched to that cost at this order size.

Share of the order left through the day for TWAP, VWAP and Almgren-Chriss, with ADBE volume by bucket
Top: share of the order still to sell. Bottom: ADBE's average volume in each 5 minute bar; its first and last 30 minutes carry 16.7% and 16.6% of the day.

Volume and vol by bucket, the optimal schedule, TWAP and VWAP

import numpy as np, pandas as pd

DATA = "https://raw.githubusercontent.com/davidalmeida90/quant-models/main/trading-models/data/"
prof = pd.read_csv(DATA + "adbe_5min_profile.csv")      # 78 buckets, ADBE averaged over 500 sessions
adbe = pd.read_json(DATA + "adbe_sessions.json", typ="series")

ADV, S0, N = adbe.average_daily_volume, adbe.last_close, len(prof)
V = prof.volume_share.values * ADV                      # shares per 5 minute bucket, the U shape
vol = prof.return_vol.values                            # return vol of each bucket
sigma_day = np.sqrt((vol ** 2).sum())                   # vol of one session

p = 0.10                                                # sell 10% of a day's volume
X = p * ADV
Y = 0.142 * p ** -0.4                                   # Almgren et al. (2005): VWAP costs 0.142 sigma p^0.6
eta = Y * sigma_day * S0 / V                            # temporary impact, $ per share per share in each bucket
s2 = (vol * S0) ** 2                                    # price variance of each bucket, $^2

def schedule(lam):
    """Shares held at the start of each bucket that minimise E[cost] + lam * Var[cost]."""
    A = np.diag(eta[:-1] + eta[1:] + lam * s2[1:]) - np.diag(eta[1:-1], 1) - np.diag(eta[1:-1], -1)
    b = np.zeros(N - 1)
    b[0] = eta[0] * X
    return np.r_[X, np.linalg.solve(A, b), 0.0]

def cost_bp(x):
    """Expected impact cost and its standard deviation, in basis points of the order."""
    n = -np.diff(x)
    return 1e4 * (eta * n ** 2).sum() / (X * S0), 1e4 * np.sqrt((s2 * x[:-1] ** 2).sum()) / (X * S0)

def half(x):
    """Clock time when half the order is sold."""
    m = 9 * 60 + 30 + 5 * int(np.argmax(x <= X / 2))
    return f"{m // 60}:{m % 60:02d}"

lams = np.geomspace(1e-9, 3e-5, 60)
lam = lams[np.argmin([abs(cost_bp(schedule(l))[1] - 110) for l in lams])]   # a risk of about 110 bp

print(f"ADBE {S0:.2f}, {ADV / 1e6:.2f}M shares a day, session vol {sigma_day:.2%}; first 30 minutes "
      f"{prof.volume_share[:6].sum():.1%} of the volume, last 30 minutes {prof.volume_share[-6:].sum():.1%}")
print(f"order: sell {X:,.0f} shares, {X * S0 / 1e6:.1f}M dollars; risk aversion {lam:.2e}")
for name, x in (("TWAP", np.linspace(X, 0, N + 1)), ("VWAP", schedule(0.0)), ("Almgren-Chriss", schedule(lam))):
    e, r = cost_bp(x)
    print(f"{name:15s} expected cost {e:5.1f} bp, risk {r:6.1f} bp, half sold by {half(x)}")
Sell 369,562 ADBE shares, 10% of daily volume, $87.1M at $235.55
ScheduleExpected costRisk, sdHalf sold by
TWAP8.1 bp152.7 bp12:45
VWAP, λ = 06.7 bp143.7 bp12:20
Almgren-Chriss, λ = 3.2e-714.6 bp110.3 bp10:00

TWAP sells the same amount every 5 minutes, as much over lunch as at the open, and pays 1.4 bp more than VWAP with 9 bp more risk: it sits inside the frontier. A risk aversion of 3.2e-7 sells half the order by 10:00, cuts the standard deviation of the cost from 143.7 to 110.3 bp and pays 14.6 bp of impact, about twice VWAP's.

Risk dwarfs cost for one day of ADBE. A session vol of 1.87% is the price of holding the shares at all, and the schedule only decides how much of it to keep. Which point to pick is a question about the trader, and the model puts a price on each answer.

Efficient frontier of expected impact cost against risk, with TWAP, VWAP and one Almgren-Chriss schedule
Every risk aversion from zero up gives one point on the frontier. TWAP sits inside it.

4. Avellaneda-Stoikov market making

A market maker quotes a bid and an ask and earns the spread when both get filled. Its risk is inventory: after a run of buys it is long just when the price may keep falling. Avellaneda and Stoikov (2008) solve for two things. A reservation price shifts both quotes away from the side already held, and an optimal spread widens with volatility and narrows when fills come easily.

r = s − q · γσ²(T − t) spread = γσ²(T − t) + (2/γ) · ln(1 + γ/k)

Here s is the mid, q the inventory, γ the risk aversion, σ the volatility, T − t the time left in the session, and k how fast fills dry up as a quote moves away from the mid. Crypto market making bots ship it as a ready strategy (Hummingbot's Avellaneda market making), and equity, futures and options market makers apply the same inventory skew.

Inputs come from 20 SPY sessions, 21 Oct to 17 Nov 2026, shipped as frequencies and volatilities only. Fills are drawn at random with probability A·exp(−kδ) per 5 minute bar, fitted to how often those bars reached each distance δ from their open (80% reach 10 cents, 32% reach 50). It is a simulation, built on the model's own assumption. One lot is 100 shares, and γ is 0.01 per lot.

Quotes then run on a later session, 25 Nov 2026, which the code downloads from Yahoo Finance: SPY went from 702.62 at the open to 716.71 at the close, +2.0%. Yahoo keeps 5 minute bars for about 60 days; after that the code says so, runs on a path simulated from the same volatilities, and prints different numbers from the ones here.

One SPY session with Avellaneda-Stoikov quotes, the reservation price, fills and inventory
SPY on 25 Nov 2026, one draw of the simulated fills. Bottom: inventory with the skew, and symmetric quotes on the same draws.

Fill intensity from real bars, quotes, and 1,000 simulated sessions

import numpy as np, pandas as pd

DATA = "https://raw.githubusercontent.com/davidalmeida90/quant-models/main/trading-models/data/"
par = pd.read_json(DATA + "as_parameters.json", typ="series")      # measured on 20 SPY sessions to 17 Nov 2026

# fill intensity A * exp(-k * delta) per 5 minute bar, fitted to how often those bars reached each distance
delta, reach = np.array(par.delta_dollars), np.array(par.reach)
slope, icpt = np.polyfit(delta, np.log(-np.log(1 - reach)), 1)
k, A, sigma = -slope, np.exp(icpt), par.session_vol
gamma = 0.01                                            # risk aversion, inventory counted in lots of 100 shares

SESSION = "2026-11-25"                                  # one fixed session, after the 20 that set the inputs
try:                                                    # Yahoo Finance keeps 5 minute bars for about 60 days
    import yfinance as yf
    g = yf.download("SPY", start=SESSION, end="2026-11-26", interval="5m", auto_adjust=False, progress=False)
    g = g.droplevel(1, axis=1) if g.columns.nlevels > 1 else g
    g = g[["Open", "High", "Low", "Close"]].set_axis(["open", "high", "low", "close"], axis=1)
    assert len(g) == 78
    path = f"real SPY path, Yahoo Finance 5 minute bars, {SESSION}"
except Exception:                                       # fallback: a path simulated from the shipped vol profile
    z = np.array(par.bucket_vol)[:, None] / np.sqrt(5) * np.random.default_rng(1).standard_normal((78, 5))
    minute = (700 * np.exp(np.cumsum(z.ravel()))).reshape(78, 5)
    op = np.r_[700.0, minute[:-1, -1]]
    g = pd.DataFrame({"open": op, "high": np.maximum(op, minute.max(1)), "low": np.minimum(op, minute.min(1)),
                      "close": minute[:, -1]})
    path = "SIMULATED path from the shipped vol profile (the download was unavailable)"
g.index = pd.date_range(SESSION + " 09:30", periods=78, freq="5min")

def session(g, u=None, skew=True):
    """One session of quotes. u: uniform draws for random fills (the simulation);
    u=None fills only when the bar's high or low reached the quote."""
    s2 = (sigma * g.open.iloc[0]) ** 2                  # dollar variance of a session
    q, cash, inv = 0, 0.0, []
    for i, (o, hi, lo) in enumerate(zip(g.open, g.high, g.low)):
        tau = 1 - i / len(g)                            # share of the session left
        spread = gamma * s2 * tau + 2 / gamma * np.log(1 + gamma / k)
        res = o - q * gamma * s2 * tau if skew else o   # reservation price
        bid, ask = res - spread / 2, res + spread / 2
        if (lo <= bid) if u is None else u[i, 0] < 1 - np.exp(-A * np.exp(-k * (o - bid))):
            q, cash = q + 1, cash - bid
        if (hi >= ask) if u is None else u[i, 1] < 1 - np.exp(-A * np.exp(-k * (ask - o))):
            q, cash = q - 1, cash + ask
        inv.append(q)
    return 100 * (cash + q * g.close.iloc[-1]), np.abs(inv).mean()

rng = np.random.default_rng(7)
runs = []
for _ in range(1000):                                   # 1,000 random fill sequences on the same path
    u = rng.random((len(g), 2))
    runs += [("inventory skew", *session(g, u, True)), ("symmetric", *session(g, u, False))]
runs.append(("skew, touch fills", *session(g)))
res = pd.DataFrame(runs, columns=["quotes", "pnl", "abs_inventory"])

s2 = (sigma * g.open.iloc[0]) ** 2
print(path)
print(f"{'SPY' if path.startswith('real') else 'simulated'} {g.open.iloc[0]:.2f} at the open, {g.close.iloc[-1]:.2f} at the close, "
      f"{g.close.iloc[-1] / g.open.iloc[0] - 1:+.2%}")
print(f"k {k:.2f} per dollar, A {A:.2f} per bar, session vol {sigma:.2%}")
print(f"spread at the open {gamma * s2 + 2 / gamma * np.log(1 + gamma / k):.2f}, at the close "
      f"{2 / gamma * np.log(1 + gamma / k):.2f}, skew per lot held at the open {gamma * s2:.2f} dollars")
print(res.groupby("quotes").agg(mean_pnl=("pnl", "mean"), sd_pnl=("pnl", "std"),
                                avg_abs_lots=("abs_inventory", "mean")).round(2).to_string())
SPY on 25 Nov 2026 x 1,000 fill draws, P&L per session in dollars
QuotesMean P&LSd of P&LLots held, average
Inventory skew, random fills+$2,555$1,2290.82
Symmetric, same spread+$2,857$7,0513.26
Inventory skew, fills only when the real bar reached the quote-$656one path0.96

Spread opens at $0.96 and closes at $0.67, and each lot held moves the quotes $0.29 at the open. Skewing for inventory gives up 11% of the average P&L, cuts its standard deviation by 83% and holds a quarter of the inventory.

Last row is the honest check. When a quote fills only if the real bar actually traded through it, fills arrive exactly when the price is moving against the market maker, and the same quotes lose $656 on the session. Random fills leave adverse selection out; live market makers fight it with queue priority, exchange rebates and fast cancels.

Distribution of simulated P&L for inventory skew and symmetric quotes on one SPY session
Same fill draws for both. Skewed quotes keep the P&L in a narrow band; symmetric quotes carry inventory into the move. Range cut at the 0.5% tails.

Over a year the comparison holds. Same model on 252 SPY sessions, 17 Nov 2025 to 17 Nov 2026, with sigma from the 20 sessions before each day and 20 fill draws a day, shared by both quoting rules. Those 5 minute bars are Alpaca SIP data, which is not redistributed, so the table below is reported from that run and the block above cannot repeat it.

252 SPY sessions x 20 fill draws, γ 0.0008, k 20 per dollar, A 85 a day, one lot a side, P&L per day in dollars
QuotesMean P&LSd of P&LLargest inventory, median day
Inventory skew+$240$7674 lots
Same spread, centred on the mid+$228$1,5936 lots

Inventory skew cuts the standard deviation of daily P&L from $1,593 to $767, with means of $228 and $240. That run sets k and A by hand for a book quoted a few cents from the mid (a spread near 11 cents), while the block above fits them to how far 5 minute bars travel, so its quotes sit about half a dollar out.


5. LLM trading agents

An LLM trading agent reads prices, news and filings, argues a view and sends an order. TradingAgents, the open source framework from Tauric Research, runs it as a committee: analysts for fundamentals, news, sentiment and technicals, a bull and a bear researcher who debate, a trader and a risk team. Coding agents such as Claude Code can trade too, given a prompt and three tools.

Funds use language models today mostly for research: reading filings, summarising calls, screening news. Letting one place the order is still an open question, and the honest way to test it is live, with every log kept.

Harness Arena put five books on Alpaca paper accounts for two sessions, 26 and 27 Oct 2026, $100,000 each, a decision every 30 minutes on the same 20 stocks. Four got one identical prompt and differ only in harness (dsh or Claude Code) and model (DeepSeek or Claude Haiku). Book five ran TradingAgents on DeepSeek. Code, minute equity marks and every report are public in Glassbench.

Equity of five AI trading books and SPY, minute by minute, on 26 and 27 Oct 2026
Alpaca equity of each book every minute, from its first mark of the day. Day one started at 13:20 New York; every book is sold at 15:50.

Both sessions from the public marks, and the luck test

import json, urllib.request
import pandas as pd

RUNS = "https://raw.githubusercontent.com/davidalmeida90/glassbench/main/arena/results/"
names = {"B1": "dsh + DeepSeek", "B2": "dsh + Haiku", "B3": "Claude Code + DeepSeek",
         "B4": "Claude Code + Haiku", "B5": "TradingAgents, DeepSeek", "SPY": "SPY"}
table, marks = {}, {}
for run in ("live-1026", "live-1027"):
    m = pd.read_csv(RUNS + run + "/marks.csv", parse_dates=["ts_utc"])  # Alpaca equity, every minute
    eq = m.groupby("book").equity
    table[run] = 100 * (eq.last() / eq.first() - 1)
    luck = json.load(urllib.request.urlopen(RUNS + run + "/report.json"))["luck"]["books"]
    table[run + " luck"] = pd.Series({b: 100 * v["percentile"] for b, v in luck.items()})
    marks[run] = m

t = pd.DataFrame(table).rename(index=names)
t["two days"] = 100 * ((1 + t["live-1026"] / 100) * (1 + t["live-1027"] / 100) - 1)
print(t[["live-1026", "live-1027", "two days", "live-1026 luck", "live-1027 luck"]].round(2).to_string())
Return from the first to the last minute mark, Alpaca equity, and the luck percentile
Book26 Oct27 OctTwo daysLuck, 26 OctLuck, 27 Oct
dsh + DeepSeek-0.52%+0.94%+0.42%5%99%
dsh + Haiku-0.38%+0.53%+0.15%8%85%
Claude Code + DeepSeek-0.63%+0.93%+0.29%1%100%
Claude Code + Haiku-0.29%+0.58%+0.29%16%90%
TradingAgents, DeepSeek+0.11%+0.42%+0.53%93%62%
SPY-0.14%+0.52%+0.38%

Two sessions are noise, and the luck test shows how much. Each book is replayed against 10,000 random books with the same number and size of trades in random stocks. Prompted books sat between the 1st and 16th percentile on the falling afternoon and between the 85th and 100th on the rally. Same habit both days, buying what had just gone up, and their own debriefs named it.

TradingAgents rated two names Overweight on day one, held 60% cash and ended the two days +0.53%, against +0.38% for SPY. After AI bills, an estimated 2 bp of slippage a trade and the real SEC fees, that comes to $478 against about $380 for SPY, and every prompted book ends below SPY.

Longer tests say less in their favour. A pilot of TradingAgents on AAPL and NVDA over the year from September 2025 rated all 8 decisions Hold, and trading its entry and stop levels lost 6.0% and 7.4% while buy and hold made 43.5% and 29.6% (method). Four decisions per stock only check the method. Glass Agents, where LLMs read the 10-K and code does the valuation, replayed its valuation core on 481 S&P 500 companies from 2015 to 2025: its ratings do not sort later returns, a 12 month rank IC of +0.018 with t at 0.8.

Each AI book's session return against the 5 to 95% range of 10,000 random books
Dot: the book's trades replayed on the same prices as the random books. Bar: 5% to 95% of 10,000 random books with the same footprint. Label: the book's percentile.

Run it

All five models in one file in the repository, with the derived tables, the charts and the output it prints. Section 4 downloads one SPY session from Yahoo Finance and section 5 reads the public Glassbench results, so both need an internet connection; sections 1 to 3 run offline after the clone.

Clone and run

git clone https://github.com/davidalmeida90/quant-models
cd quant-models/trading-models
pip install -r ../requirements.txt
python model.py          # output.txt, results.json and charts/

Limitations


Every run on one line

Real data unless noted
ModelDataResult
GEXSPX chain, 9 Sep 2026-$40.7bn per 1%, flip 7,667
Gamma scalpingpaper fills, 2 Nov 2026+$899.79, of which +$886 from implied vol
Almgren-ChrissADBE bars, 500 sessions14.6 bp cost for 110.3 bp risk, VWAP 6.7 for 143.7
Avellaneda-StoikovSPY, 25 Nov 2026, simulated fills+$2,555 a session, sd $1,229; -$656 on touch fills
LLM trading agentsAlpaca paper, 2 sessionsTradingAgents +0.53%, SPY +0.38%