Python API
Use AlphaLensClient directly from Python for hosted auth, backtests, live sessions, and data helpers.
Use the Python API when you want AlphaLens wiring inside scripts, notebooks, or your own research runner.
Create a client
Pass the API key directly:
from alphalens_core import AlphaLensClient
al = AlphaLensClient(api_key="alens_...")Or let the client read ALPHALENS_API_KEY:
from alphalens_core import AlphaLensClient
al = AlphaLensClient()Do not put API keys or broker credentials on the strategy class.
Run a backtest
from alphalens_core import AlphaLensClient
from my_strategy import MomentumRotation
al = AlphaLensClient(api_key="alens_...")
result = al.backtest(MomentumRotation)
print(result.stats)run is an alias for backtest:
result = al.run(MomentumRotation)The strategy class still owns defaults such as start, end, universe, resolution, and benchmark_symbol.
Start a live session
from alphalens_core import AlphaLensClient
from my_strategy import MomentumRotation
al = AlphaLensClient(api_key="alens_...")
session = al.live(
MomentumRotation,
broker="alpaca",
paper=True,
deployment_name="MomentumRotation paper",
)
session.run()Common options:
| Option | Purpose |
|---|---|
broker | Broker backend, currently alpaca |
paper | True for Alpaca paper, False for live |
history_bars | Number of bars seeded before live processing |
history_max_bars | Maximum rolling bars retained |
state_path | Restart checkpoint file |
poll_interval_sec | Poll cadence while waiting for completed bars |
idle_log_interval_sec | Cadence for idle waiting logs |
deployment_id | Reuse an existing Strategy Center deployment |
deployment_name | Display name in Strategy Center |
telemetry | Disable with False for local-only runs |
algorithm_kwargs | Constructor parameters passed to the strategy |
Pass strategy parameters
If your strategy exposes parameters, pass them through the live runner:
session = al.live(
MomentumRotation,
broker="alpaca",
paper=True,
algorithm_kwargs={"lookback": 126, "top_n": 2},
)For CLI runs, use repeated --param key=value flags.
Hosted market data cache
cache = al.cache(cache_dir=".alphalens/cache")The hosted cache uses AlphaLens-authenticated market data endpoints. This lets local users avoid managing a separate Polygon key for the hosted workflow.
Error handling
AlphaLens sync failures should be treated as operational warnings, not trading signals. A local live process should keep running if telemetry is temporarily unavailable.