Alpheo algo format, v0.1
An Alpheo algo is one Python file containing two settings and one function.
SYMBOLS = ["AAPL"] # 1 to 10 symbols from the Alpheo universe
TIMEFRAME = "1d" # "1m", "5m", "1h" or "1d"
def on_bar(data, weights, state):
closes = data["AAPL"]["close"]
if len(closes) < 50:
return {} # all cash
if closes.iloc[-10:].mean() > closes.iloc[-50:].mean():
return {"AAPL": 1.0} # 100% in Apple
return {}
What on_bar receives
Alpheo calls on_bar once at the close of every bar.
| Argument | What it is |
|---|---|
data | A dict with one pandas DataFrame per symbol in SYMBOLS. Columns: open, high, low, close, volume. Indexed by bar time (New York time), oldest first. The last row is the bar that just closed. |
weights | A dict of what the account currently holds, as a share of its value, e.g. {"AAPL": 0.98}. Empty means all cash. |
state | A dict you can use to remember things between bars. Change it in place (state["x"] = 1); don't replace it. |
History: up to the last 1,000 bars on 1m, 5m and 1h, and up to the last 252 bars (about a year) on 1d. Early in a run there is less, so always check len(...) before using long lookbacks.
Bar sizes: 1-minute ("1m"), 5-minute ("5m"), hourly ("1h") and daily ("1d"). Intraday bars start at 9:30 (so 5-minute bars run 9:30, 9:35 ... 15:55, and hourly bars 9:30, 10:30 ... 15:30, the last being half an hour). Daily bars are labelled with the date.
Shorter bars mean many more calls: a year is 252 daily bars, 1,764 hourly bars, 19,656 5-minute bars or 98,280 1-minute bars. Keep on_bar quick on 1m and 5m. A backtest that will probably take longer than a minute asks you before it starts, and you choose whether to wait.
Bars cover US regular trading hours only (9:30am to 4pm New York time).
What on_bar must return
Target weights: the share of the account you want in each symbol.
{"AAPL": 0.5, "MSFT": 0.3}means 50% Apple, 30% Microsoft, 20% cash.{}means all cash.- Each weight is a number from 0 to 1. Together they must add up to 1 or less. (A small overshoot, up to 1.05, is scaled back to 1 with a warning.)
- Only symbols listed in
SYMBOLS. - No shorting or leverage in v0.
To keep your current positions, return dict(weights).
How trades happen
- The account starts with $10,000 of paper money.
- After
on_barreturns, the account moves to the new weights at the next bar's open. You can never trade at a price you've already seen. - Every trade pays 0.05% slippage. There is no commission.
- Changes smaller than 2% of the account are ignored, so tiny adjustments don't cost anything.
Rules
- Allowed imports:
numpy,pandas,scipy,sklearn,ta, and the standard modulesmath,statistics,collections,itertools,functools,datetime,typing,dataclasses,enum,random. - No internet, files or system access. All data arrives through
data. - Not allowed:
open,exec,eval,compile,__import__,input,globals,locals,vars,getattr,setattr,delattr, and special attributes like__class__. - Only imports, constants, functions and classes at the top level of the file.
- Each call to
on_barmust finish within 2 seconds. statemay only hold simple values (numbers, text, lists, dicts), up to 100 KB.- Keep everything you need between bars in
state. The live record restarts your algo every night and onlystatecarries over, soglobalandnonlocalare not allowed. - Randomness is seeded, so the same code on the same bars always makes the same decisions. Use the bar times in
data, not the clock (datetime.now(),date.today()and similar are rejected): the live record runs after the market closes. - File size limit: 200 KB.
- If
on_barcrashes, times out or returns something invalid, nothing changes for that bar. After 10 errors in one trading day, or 10 in a row, the algo is paused: all positions are closed at the next bar's open, it stops trading, and its record stops at that point until a fixed version is uploaded.
How algos are ranked
Only the live record counts, never a backtest. An algo joins the Algos leaderboard after 20 trading days live, ranked by Sharpe ratio (risk-adjusted return) with total return shown beside it. Creators are ranked on a portfolio of their own algos that they declare and lock in advance. Full rules: docs/LEADERBOARD.md.
Universe (v0, 50 symbols)
Index ETFs: SPY, QQQ, IWM, DIA
Sector ETFs: XLK, XLF, XLE, XLV, XLI, XLY, XLP, XLU, XLB, XLRE, XLC
Stocks: AAPL, MSFT, NVDA, AMZN, GOOGL, META, TSLA, AVGO, JPM, V, MA, UNH, XOM, LLY, JNJ, PG, HD, COST, WMT, BAC, KO, PEP, ABBV, MRK, CVX, ORCL, CRM, AMD, NFLX, ADBE, CSCO, INTC, DIS, MCD, QCOM
Error codes
| Code | Meaning |
|---|---|
| E100 | File too large |
| E101 | Syntax error or not plain text |
| E102 | Empty file |
| E110 | Import not allowed |
| E111 | Banned built-in used (files, code execution) |
| E112 | Special attribute access |
| E120 | Code at the top level that isn't an import, constant, function or class |
| E121 | global or nonlocal used (keep values in state instead) |
| E122 | Reads the current date or time (use the bar's time from data) |
| E130 | SYMBOLS missing or not a plain list |
| E131 | Wrong number of symbols |
| E132 | Symbol not in the universe, or listed twice |
| E133 | TIMEFRAME missing or invalid |
| E140 | on_bar missing or async |
| E141 | on_bar doesn't take exactly (data, weights, state) |
| E200 | on_bar crashed |
| E201 | Didn't return a dict of weights |
| E202 | Returned a symbol not in SYMBOLS |
| E203 | A weight isn't a number between 0 and 1 (or is NaN) |
| E204 | Weights add up to more than 1 |
| E205 | Took longer than the time limit |
| E206 | state holds something unsaveable or too large |
| E207 | Paused after too many errors |
| E208 | File failed to load |
| E209 | Process stopped unexpectedly (usually memory) |
| W120 | Warning: if __name__ == "__main__" block is ignored |
| W204 | Warning: weights added up to slightly more than 1 and were scaled back |
Prefer to use an AI?
These prompts give ChatGPT, Claude or any other AI everything in the spec above. Add your idea or your existing code and upload the file it gives back. It's checked and measured exactly like any other algo.