Skip to main content

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.

Host on AlphaLens

AlphaLens can host the dashboard side of your alphalens-core workflow: backtest sync, Strategy Center dashboards, hosted market data access, and live deployment telemetry. Your strategy code and broker execution still run locally in v1.

Install the extras used by the hosted workflow:

pip install "alphalens-core[live,cloud,fast]"

Create an API key in AlphaLens Settings, then connect locally:

alphalens connect --api-key alens_...
alphalens status

Run and sync a backtest:

alphalens run --strategy my_strategy:MyStrategy

For CI or one-off shells, ALPHALENS_API_KEY=alens_... alphalens run ... is also supported. End users should not need internal Supabase commands.

Run a local Alpaca paper deployment and stream telemetry to Strategy Center:

alphalens live --strategy my_strategy:MyStrategy

Use the Python API when you want key injection from code:

from alphalens_core import AlphaLensClient
from my_strategy import MyStrategy

al = AlphaLensClient(api_key="alens_...")
result = al.backtest(MyStrategy)
al.live(MyStrategy, broker="alpaca", paper=True).run()

Read the hosted workflow docs at alphalens.dev/docs/alphalens-core, including the strategy authoring guide at alphalens.dev/docs/alphalens-core/build-a-strategy.

Live / Alpaca Paper Trading

The live runner uses the same Algorithm class and history API as the backtester. The simplest path is the built-in Alpaca + Polygon runner:

export POLYGON_API_KEY=...
export ALPACA_API_KEY=...
export ALPACA_SECRET_KEY=...

alphalens live --strategy my_strategy:MyStrategy

alphalens live defaults to Alpaca paper trading. Pass --live only when you intend to route orders to the live Alpaca account. The command reads class.universe and class.resolution by default; override them with --universe SPY,QQQ or --resolution 5minute.

For custom broker/data transports, 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(), and history_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 PolygonCompletedBarPoller for the built-in Polygon polling implementation. 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 HTML result.dashboard, and quantstats reports.

CLI

alphalens run --strategy mymod:MyStrategy
alphalens live --strategy mymod:MyStrategy
alphalens wfa --strategy mymod:MyStrategy --train 504 --test 63 --step 63
alphalens cache --info

License

Apache-2.0 © AlphaLens LLC

Metadata

Release files for alphalens-core 0.3.36

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for alphalens-core 0.3.36
File Size Uploaded Provenance Actions
alphalens_core-0.3.36.tar.gz 356.0 kB With provenance Details for alphalens_core-0.3.36.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for alphalens-core 0.3.36
File Interpreter ABI Platform Actions
alphalens_core-0.3.36-py3-none-any.whl Python 3 none any Details for alphalens_core-0.3.36-py3-none-any.whl

Total release size: 681.3 kB

Release files / alphalens_core-0.3.36.tar.gz

Download URL alphalens_core-0.3.36.tar.gz
Size 356.0 kB
Tags Source
SHA-256 checksum
How to use checksums
e125f32a3785bd4035d0561581427f852a4ff3bd5240fa17ccbe5933bd228549
BLAKE2b-256 checksum
How to use checksums
40da6e2d6f24ea1d8ba08bb5eea895690e80268b1cf0deda5ace050257e3cb23
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jun 23, 2026.

Transparency log

Release files / alphalens_core-0.3.36-py3-none-any.whl

Download URL alphalens_core-0.3.36-py3-none-any.whl
Size 325.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0ce02c6d149ffd92ab1539668ef55e101b79e3afc8fe0091b042b160c597f932
BLAKE2b-256 checksum
How to use checksums
a0e2b83279a858eefed6199c0b4ed004777d89bf5cae7b0a8a374c5bb0eb7573
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jun 23, 2026.

Transparency log

Security for alphalens-core 0.3.36

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for alphalens_core-0.3.36.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jun 23, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.3.36 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page