API Reference
Auto-generated from source code docstrings. For a guided walkthrough with examples, see the API Overview.
Core
Portfolio
Portfolio
Tree node holding mutable simulation state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Display name for this portfolio node. |
required |
algos
|
list[Algo]
|
Ordered list of algos forming the strategy pipeline. |
required |
children
|
list[str] | list[Any] | None
|
Leaf tickers (list of str) or child Portfolio nodes. |
required |
Backtest
Backtest
Configures a backtest run. Validates data at construction time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
portfolio
|
Portfolio
|
Root portfolio node defining the strategy. |
required |
data
|
dict[str, DataFrame]
|
Dict mapping ticker symbols to OHLCV DataFrames. |
required |
config
|
TiConfig | None
|
Simulation parameters. Uses defaults if not provided. |
None
|
run
run(*tests, leverage=1.0)
Run one or more backtests and return a BacktestResult.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tests
|
Backtest
|
One or more Backtest objects. |
()
|
leverage
|
float | list[float]
|
Leverage multiplier. A single float applies to all backtests; a list applies per-backtest (must match length). Default 1.0. |
1.0
|
TiConfig
TiConfig
dataclass
Global simulation parameters. Pass a custom instance to Backtest(config=...) to override.
Data
fetch_data
fetch_data(tickers, start, end, source='yfinance', csv=None)
Fetch OHLCV data. Returns dict keyed by ticker, each with UTC DatetimeIndex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tickers
|
list[str]
|
List of ticker symbols. |
required |
start
|
str
|
Start date string (e.g. "2019-01-01"). |
required |
end
|
str
|
End date string (e.g. "2024-12-31"). |
required |
source
|
str
|
Data source — "yfinance" or "alpaca". |
'yfinance'
|
csv
|
str | dict[str, str] | None
|
Optional CSV source for offline loading. Either:
- A directory path (str) — auto-discovers |
None
|
Falls back to the other source once on failure.
validate_data
validate_data(data, extra=None)
Check all DataFrames share identical DatetimeIndex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, DataFrame]
|
Dict mapping ticker symbols to OHLCV DataFrames. |
required |
extra
|
dict[str, DataFrame] | None
|
Optional additional DataFrames to validate (e.g., VIX data). |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If any DataFrame has a different DatetimeIndex. |
Signals
Signal
Namespace for signal algos (when to rebalance).
Schedule
Bases: Algo
Returns True when context.date matches the schedule rule.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
day
|
int | str
|
"start", "mid", "end", or an int (1-31) for a specific day-of-month. |
'end'
|
month
|
int | None
|
Optional — restrict to a specific month (1-12). |
None
|
closest_trading_day
|
bool
|
Snap to nearest valid trading day. Default True. |
True
|
Once
Bases: Algo
Fires True on the first call, False on all subsequent calls.
Use for buy-and-hold strategies: buy once, then hold forever.
Monthly
Quarterly
Bases: Algo
Fires on specified months (default Jan, Apr, Jul, Oct). Delegates to Or(Schedule...).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
months
|
list[int] | None
|
Month numbers (1-12) to fire on. Default [1, 4, 7, 10]. |
None
|
day
|
int | str
|
Day parameter passed to each Schedule. Default "end". |
'end'
|
Weekly
Bases: Algo
Fires once per ISO week on a configured day.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
day
|
str
|
"start" (Monday), "mid" (Wednesday), or "end" (Friday). Default "end". |
'end'
|
closest_trading_day
|
bool
|
Snap to nearest valid trading day. Default True. |
True
|
Yearly
Bases: Algo
Fires once per year. Day resolves at year level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
day
|
int | str
|
"start" (Jan), "mid" (Jul), "end" (Dec), or int (day-of-month). |
'end'
|
month
|
int | None
|
Override target month. Default derived from day mode. |
None
|
EveryNPeriods
Bases: Algo
Fires every N-th period boundary on a configured day within the period.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Fire every N periods. |
required |
period
|
str
|
"day", "week", "month", or "year". |
required |
day
|
str
|
"start", "mid", "end" — which day within the period. Default "end". |
'end'
|
VIX
Bases: Algo
Regime switching based on VIX level with hysteresis.
Writes to both context.selected and context.weights: - VIX < low → children[0] (low-vol / risk-on) - VIX > high → children[1] (high-vol / risk-off) - Between thresholds → previous selection persists
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
high
|
float
|
Upper VIX threshold. |
required |
low
|
float
|
Lower VIX threshold. |
required |
data
|
dict[str, DataFrame]
|
Dict containing "^VIX" DataFrame with close prices. |
required |
Indicator
Bases: Algo
Fires on technical indicator state transitions (crossovers).
The condition function receives a Series of close prices over the lookback window and returns a boolean state (e.g., SMA50 > SMA200). The algo fires True only when that state transitions: - cross="up": False → True (e.g., golden cross) - cross="down": True → False (e.g., death cross) - cross="both": any state change
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
Which ticker's prices to evaluate. |
required |
condition
|
Callable[[Series], bool]
|
Receives close prices Series, returns bool state. |
required |
lookback
|
DateOffset
|
How far back to slice prices for the condition. |
required |
cross
|
str
|
Transition direction — "up", "down", or "both". |
'up'
|
Selection
Select
Namespace for select algos (what to include).
All
Momentum
Bases: Algo
Selects top-N tickers by cumulative return over a lookback window.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of tickers to select. |
required |
lookback
|
DateOffset
|
Length of the return lookback window. |
required |
lag
|
DateOffset
|
Offset from current date to avoid look-ahead bias. |
DateOffset(days=1)
|
sort_descending
|
bool
|
True for top performers, False for worst. |
True
|
Filter
Bases: Algo
Boolean gate using external data. Returns False to halt the algo queue.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, DataFrame]
|
Dict of extra DataFrames (e.g. VIX data). |
required |
condition
|
Callable[[dict[str, Series]], bool]
|
Callable receiving current-date rows, returns True/False. |
required |
Weighting
Weigh
Namespace for weigh algos (how much to allocate).
Equally
Ratio
Bases: Algo
Assigns explicit weights, normalised to sum(|w|) = 1.0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
dict[str, float]
|
Dict mapping ticker/name to target weight. Tickers in selected but missing from weights get weight 0. |
required |
BasedOnHV
Bases: Algo
Scales initial_ratio to target annualised portfolio volatility.
Uses diagonal covariance approximation: portfolio_hv = sqrt(sum((w * hv)^2))
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial_ratio
|
dict[str, float]
|
Starting weight allocation per ticker. |
required |
target_hv
|
float
|
Target annualised volatility as decimal (0.15 = 15%). |
required |
lookback
|
DateOffset
|
Window for computing historical volatility. |
required |
BasedOnBeta
Bases: Algo
Scales initial_ratio weights to achieve a target portfolio beta.
Computes per-asset beta against a benchmark using OLS over the lookback window, then iteratively adjusts weights until portfolio beta converges to the target.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial_ratio
|
dict[str, float]
|
Starting weight allocation per ticker. |
required |
target_beta
|
float
|
Target portfolio beta (0 = market-neutral). |
required |
lookback
|
DateOffset
|
Window for computing rolling betas. |
required |
base_data
|
DataFrame
|
Benchmark OHLCV DataFrame (e.g. SPY), passed directly. |
required |
ERC
Bases: Algo
Equal Risk Contribution (Risk Parity) weighting.
Sizes each asset so every position contributes the same amount of risk to the total portfolio. Delegates optimisation to riskfolio-lib.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lookback
|
DateOffset
|
Window for computing the covariance matrix. |
required |
covar_method
|
str
|
Covariance estimation method — "ledoit-wolf", "hist", or "oas". |
'ledoit-wolf'
|
risk_parity_method
|
str
|
Solver — "ccd" or "slsqp" (unused directly; riskfolio uses its own solver). |
'ccd'
|
maximum_iterations
|
int
|
Max solver iterations. |
100
|
tolerance
|
float
|
Convergence tolerance. |
1e-08
|
Actions
Action
Results
BacktestResult
BacktestResult
Collection of backtest results. Always wraps a list, even for single backtests.
summary()
Summary across all backtests. For single result, delegates directly.
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with key metrics. Single backtest: one 'value' column. |
DataFrame
|
Multiple backtests: one column per portfolio name. |
full_summary()
Full summary across all backtests.
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with extended metrics including period returns, |
DataFrame
|
daily/monthly/yearly stats, and drawdown analysis. |
plot(interactive=False)
Plot all backtest equity curves.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interactive
|
bool
|
Use Plotly instead of matplotlib. Requires plotly extra. |
False
|
Returns:
| Type | Description |
|---|---|
Any
|
matplotlib Figure or plotly Figure object. |
plot_histogram()
Plot return distribution for all backtests.
plot_security_weights()
Plot security weights for all backtests.
Base Classes
Algo
Algo
Bases: ABC
Base class for all algo-stack components.
__call__(context)
abstractmethod
Return True to continue the AlgoQueue, False to abort.
Context
Context
dataclass
Passed to every Algo.call. Carries read-only inputs and mutable inter-algo state.