AlphaLens — an event-driven backtesting & walk-forward engine for systematic strategies
Project description
alphalens-core
An event-driven backtesting & walk-forward engine for systematic trading strategies.
Write a strategy as a Python class, run a single forward pass over an in-memory
OHLCV feed, and get back an equity curve, a trade log, and a rich set of
performance statistics — plus walk-forward analysis, parameter sweeps, and an
HTML dashboard. alphalens-core is the open engine behind AlphaLens.
Install
pip install alphalens-core # core engine (pandas + numpy only)
pip install "alphalens-core[viz]" # + matplotlib / quantstats dashboard & reports
pip install "alphalens-core[polygon]" # + Polygon market-data fetching
pip install "alphalens-core[live]" # + Alpaca execution and Polygon history
pip install "alphalens-core[fast]" # + pyarrow parquet cache
Quickstart
from alphalens_core import Algorithm, Backtester
class GoldenCross(Algorithm):
start = "2020-01-01"
end = "2024-12-31"
universe = ["SPY"]
def initialize(self):
self.set_warmup(50)
def on_data(self, slice):
hist = self.history("SPY", 50)["close"]
if len(hist) < 50:
return
self.set_holdings("SPY", 1.0 if hist.tail(10).mean() > hist.mean() else 0.0)
result = Backtester().run(GoldenCross)
print(result.stats) # Sharpe, Sortino, CAGR, max drawdown, win rate, …
result.dashboard # inline HTML report in Jupyter, or opens in your browser
Live data needs a POLYGON_API_KEY (a .env / .env.local file is loaded
automatically). To run fully offline, inject your own DataFeed.
Live / Alpaca Paper Trading
The live runner uses the same Algorithm class and history API as the
backtester. LiveSession.from_cache seeds a bounded rolling history, then each
completed Slice is appended before on_data runs:
from alphalens_core import AlpacaBrokerage, LiveSession, NO_BAR
from my_data import next_completed_slice
from my_strategy import MyStrategy
broker = AlpacaBrokerage(paper=True)
session = LiveSession.from_cache(
MyStrategy,
brokerage=broker,
next_bar_fn=next_completed_slice, # Slice, NO_BAR while idle, None to stop
history_bars=500,
state_path=".alphalens/live/my_strategy.json",
)
session.run()
from_cache uses UniverseCache and Polygon by default; inject an existing
cache to use another DataSource. The runner:
- exposes seeded and appended bars through
history(),history_array(), andhistory_arrays(); - keeps history bounded and suppresses duplicate timestamps;
- rejects out-of-order bars and unreconciled broker orders;
- synchronizes Alpaca cash/positions and FIFO lots at startup;
- respects strategy resolution and warmup settings;
- checkpoints the last processed bar to avoid replay after restart.
Market-data transport is intentionally separate from execution. A callback
must emit completed, consolidated slices for the strategy universe. See
alphalens_core.examples.paper_trade for an Alpaca polling example.
Live membership changes are not yet supported: the session fails explicitly
for dynamic universes until removal orders can be reconciled with broker fills.
Features
- Event-driven lifecycle —
initialize,on_data,on_order_event,on_securities_changed,on_end_of_day,on_warmup_finished. - Realistic fills — next-bar execution with pluggable slippage / fee / fill models, and a one-bar look-ahead guard so decisions on bar t can't peek at bar t's close.
- Walk-forward analysis with per-fold parameter search.
- Parameter sweeps + PBO (probability of backtest overfitting).
- Live execution through Alpaca paper/live brokerage with buffered rolling history and restart-safe bar processing.
- Reporting —
result.stats, an HTMLresult.dashboard, and quantstats reports.
CLI
alphalens run --strategy mymod:MyStrategy
alphalens wfa --strategy mymod:MyStrategy --train 504 --test 63 --step 63
alphalens cache --info
License
Apache-2.0 © AlphaLens LLC
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file alphalens_core-0.3.7.tar.gz.
File metadata
- Download URL: alphalens_core-0.3.7.tar.gz
- Upload date:
- Size: 319.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
10047afe0844a32163960aa868273bb8701152f29a04b9dee710107373217998
|
|
| MD5 |
6c981e10bc0e429bbec2174432b8c58f
|
|
| BLAKE2b-256 |
8e63d0f41d9673f85477054a3ea0e8d6b2046f0b971c71e60dcf45683b3188e5
|
File details
Details for the file alphalens_core-0.3.7-py3-none-any.whl.
File metadata
- Download URL: alphalens_core-0.3.7-py3-none-any.whl
- Upload date:
- Size: 295.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b576aa5312ade68c5a3e69782d70eca0d70736b5eb146e4dde5b9060a931f225
|
|
| MD5 |
f5bcd2df6a6c13eb22735a3e8c18f37c
|
|
| BLAKE2b-256 |
69472e4f6e9e49989d79386f26906adf60c9a35a493c9f063f3e824112086f2a
|