Fast minimalist vector-based grid search and backtesting for perpetual futures.
Project description
Alphavec
Disclaimer
The content provided in this project is for informational purposes only and does not constitute financial advice. This information should not be construed as professional financial advice, and it is recommended to consult with a qualified financial advisor before making any financial decisions.
No liability is accepted for any losses or damages incurred as a result of acting or refraining from action based on the information provided in this project. Use this information at your own risk.
$$\ $$\
$$ | $$ |
$$$$$$\ $$ | $$$$$$\ $$$$$$$\ $$$$$$\ $$\ $$\ $$$$$$\ $$$$$$$\
\____$$\ $$ |$$ __$$\ $$ __$$\ \____$$\\$$\ $$ |$$ __$$\ $$ _____|
$$$$$$$ |$$ |$$ / $$ |$$ | $$ | $$$$$$$ |\$$\$$ / $$$$$$$$ |$$ /
$$ __$$ |$$ |$$ | $$ |$$ | $$ |$$ __$$ | \$$$ / $$ ____|$$ |
\$$$$$$$ |$$ |$$$$$$$ |$$ | $$ |\$$$$$$$ | \$ / \$$$$$$$\ \$$$$$$$\
\_______|\__|$$ ____/ \__| \__| \_______| \_/ \_______| \_______|
$$ |
$$ |
\__|
Alphavec is a lightning fast, minimalist, cost-aware vectorized backtest engine inspired by the guys at RobotWealth.
The backtest input is the natural output of a typical quant research process - a time series of portfolio weights. You simply provide a dataframe of weights and a dataframe of close prices and order prices, along with some optional cost parameters and the backtest returns a streamlined performance report with insight into the key metrics.
alphavec has first-class support for simulating leveraged perptual futures strategies using a small, fast, verifiable simulation core.
Rationale
Alphavec is an antidote to the various bloated and complex backtest frameworks.
To validate ideas all you really need is...
weights * returns.shift(-1)
The goal was to add just enough extra complexity to this basic formula to support sound development of cost-aware systematic trading strategies.
Install
Requires Python >=3.10
pip install alphavec
- From source:
python3 -m venv .venv./.venv/bin/pip install -e .
- For development:
./.venv/bin/pip install -e ".[dev]"
Usage
Notes
- Simulates cross‑margin (cash pooling) with unlimited leverage and borrowing (no liquidations or margin calls).
- Orders execute at
order_pricesplus slippage and fees. - Funding applies per period using signed
funding_rates, +ve rate shorts earn, longs pay, and vice versa for a -ve rate. - NaNs in
order_pricesorclose_pricesimply the asset is not tradable that period. - NaNs in
funding_ratesare treated as 0, and funding is always 0 whenclose_pricesis NaN. - Positions will always be closed if target weight is zero, regardless of minimum notional filter.
Simulation
simulate() runs a cross‑margin perpetual futures backtest from target portfolio weights.
Key inputs:
weights: pandasDataFramewith aDatetimeIndexand columns for each asset. Values are decimal percentage target weights (1.0 = 100% equity invested). Positive = long, negative = short. Weights may sum greater than 1 at a time period for leverage.close_prices,order_prices,funding_rates(optional): same shape/index/columns asweights.
Returns:
returns: period returns as a pandasSeries.metrics: key performance metrics as a pandasDataFramewithValueandNotecolumns.
Example:
See examples/simulate.ipynb
import pandas as pd
from alphavec import MarketData, SimConfig, simulate, tearsheet
weights = pd.DataFrame({"BTC": [1, 1, 1]}, index=pd.date_range("2024-01-01", periods=3, freq="1D"))
close_prices = pd.DataFrame({"BTC": [100, 105, 110]}, index=weights.index)
order_prices = close_prices.shift(1).fillna(close_prices.iloc[0])
result = simulate(
weights=weights,
market=MarketData(close_prices=close_prices, order_prices=order_prices, funding_rates=None),
config=SimConfig(
benchmark_asset="BTC",
order_notional_min=10,
fee_rate=0.00025, # 2.5 bps per trade
slippage_rate=0.001, # 10 bps per trade
init_cash=10_000,
freq_rule="1D",
trading_days_year=365,
risk_free_rate=0.03,
),
)
html_str = tearsheet(
sim_result=result,
output_path="tearsheet.html",
signal_smooth_window=30,
rolling_sharpe_window=30,
)
Parameter Search
grid_search() wraps simulate() and runs a 2D grid search where the objective is a simulation metric (default: Annualized Sharpe).
See examples/search.ipynb
from alphavec import Grid2D, MarketData, SimConfig, grid_search
results = grid_search(
generate_weights=generate_weights, # def generate_weights(params: Mapping) -> pd.DataFrame
base_params={"foo": 1},
param_grids=[
Grid2D("lookback", [5, 10, 20], "leverage", [0.5, 1.0, 2.0]),
],
market=MarketData(close_prices=close_prices, order_prices=order_prices, funding_rates=None),
config=SimConfig(),
)
results.table
results.heatmap_figure(grid_index=0).show()
results.best.metrics
results.best.result
Metrics
simulate() returns a metrics DataFrame with Category, Value, and Note columns. Metrics are grouped into categories:
Categories
- Meta: Simulation metadata and configuration
- Performance: Returns, volatility, Sharpe ratio, drawdowns
- Costs: Fees, funding, turnover, order statistics
- Exposure: Gross/net leverage metrics
- Benchmark: Alpha, beta, tracking error, information ratio (CAPM)
- Distribution: Win/loss stats, skewness, kurtosis, drawdown duration
- Portfolio: Holding periods, weights, cost ratios
- Risk: Sortino, VaR, CVaR, Omega, downside deviation, Ulcer Index
- Signal: ICs, decile spreads, hit-rates, and selection vs directional decomposition (vs next-period returns)
Additional Diagnostics (for charting)
Some richer time series / grouped diagnostics are attached as metrics.attrs[...] for use in the tearsheet:
metrics.attrs["equity"]: equity curve (Series)metrics.attrs["benchmark_equity"]: benchmark equity curve whenbenchmark_assetis provided (Series)metrics.attrs["weight_forward"]: per-period signal diagnostics vs next returns (DataFrame), including:ic,rank_ictop_bottom_spread- selection vs directional attribution (and per-gross variants)
metrics.attrs["weight_forward_deciles"]: mean next return by weight decile (Series)metrics.attrs["weight_forward_deciles_median"]: median next return by weight decile (Series)metrics.attrs["weight_forward_deciles_std"]: std dev of next return by weight decile (Series)metrics.attrs["weight_forward_deciles_count"]: observation countnby weight decile (Series)metrics.attrs["alpha_decay_next_return_by_type"]: alpha decay curve as a DataFrame indexed by lag (periods), with mean next return per gross and t-stats for:total_per_gross_*,selection_per_gross_*,directional_per_gross_*
n is the number of (asset, timestamp) observations that fell into that decile with a non-zero weight and a finite next-period return.
Statistical Methodology
Alphavec follows industry-standard statistical practices for backtesting:
- Sample statistics (Bessel's correction,
ddof=1) for all variance/standard deviation calculations- Rationale: Backtests are samples from possible market outcomes, not complete populations
- Aligns with quantstats, empyrical, pyfolio, and academic finance literature
- Geometric mean for total returns (compounds properly over time)
- Arithmetic mean for active returns (matches tracking error calculation for Information Ratio)
- Sample covariance for beta calculation (CAPM-consistent)
- Excess kurtosis (normal distribution = 0, not 3)
This ensures alphavec metrics are directly comparable to industry benchmarks and professional analytics platforms.
Tearsheet
The built-in tearsheet() renderer produces a self-contained HTML report (static charts + metrics table), including:
- Equity curve (portfolio and optional benchmark)
- Drawdown
- Rolling Sharpe (configurable via
rolling_sharpe_window, default30) - Returns distribution
- Signal diagnostics (when available): IC / Rank IC, top-bottom decile spread, attribution, alpha decay by lag (total/selection/directional), and decile charts (mean/median/Sharpe) with per-decile
nshown on the x-axis
Tearsheet Example
Project details
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 alphavec-0.3.0.tar.gz.
File metadata
- Download URL: alphavec-0.3.0.tar.gz
- Upload date:
- Size: 37.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d36f832ce4823334e654d9c4dbeaa30f2a8966a5f27f3a141401397566be328a
|
|
| MD5 |
a5219cf00ac648aff58ce9f6878eaf5b
|
|
| BLAKE2b-256 |
7f510ff671a86d07db24264747313bff359632319830702fa35887dd77b1dec9
|
Provenance
The following attestation bundles were made for alphavec-0.3.0.tar.gz:
Publisher:
python-publish.yml on breaded-xyz/alphavec
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
alphavec-0.3.0.tar.gz -
Subject digest:
d36f832ce4823334e654d9c4dbeaa30f2a8966a5f27f3a141401397566be328a - Sigstore transparency entry: 765815468
- Sigstore integration time:
-
Permalink:
breaded-xyz/alphavec@e9066e682fcf9ccc85800b3912c82b89a5073922 -
Branch / Tag:
refs/tags/v.0.3.0 - Owner: https://github.com/breaded-xyz
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@e9066e682fcf9ccc85800b3912c82b89a5073922 -
Trigger Event:
release
-
Statement type:
File details
Details for the file alphavec-0.3.0-py3-none-any.whl.
File metadata
- Download URL: alphavec-0.3.0-py3-none-any.whl
- Upload date:
- Size: 31.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7c8db203b123c3d8e9b60abb0874d3aa1a1045469d199dd3c8f4bc2324f54a12
|
|
| MD5 |
adb96c3a608d32c16582c38053a4cc74
|
|
| BLAKE2b-256 |
f2b9847e308ffdeca45fc8806dd914bfc1e16f0ed4e911ce66e9b3c0a9f6171c
|
Provenance
The following attestation bundles were made for alphavec-0.3.0-py3-none-any.whl:
Publisher:
python-publish.yml on breaded-xyz/alphavec
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
alphavec-0.3.0-py3-none-any.whl -
Subject digest:
7c8db203b123c3d8e9b60abb0874d3aa1a1045469d199dd3c8f4bc2324f54a12 - Sigstore transparency entry: 765815474
- Sigstore integration time:
-
Permalink:
breaded-xyz/alphavec@e9066e682fcf9ccc85800b3912c82b89a5073922 -
Branch / Tag:
refs/tags/v.0.3.0 - Owner: https://github.com/breaded-xyz
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@e9066e682fcf9ccc85800b3912c82b89a5073922 -
Trigger Event:
release
-
Statement type: