Skip to main content

Fast minimalist vector-based backtesting for perpetual futures.

Project description

Alphavec

CI

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_prices plus 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_prices or close_prices imply the asset is not tradable that period.
  • NaNs in funding_rates are treated as 0, and funding is always 0 when close_prices is 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: pandas DataFrame with a DatetimeIndex and 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 as weights.

Returns:

  • returns: period returns as a pandas Series.
  • metrics: key performance metrics as a pandas DataFrame with Value and Note columns.

Example:

See examples/example.ipynb

import pandas as pd
from alphavec import 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.shift(1).fillna(close.iloc[0])

returns, metrics= simulate(
    weights=weights,
    close_prices=close_prices,
    order_prices=order_prices,
    funding_rates=funding_rates,
    benchmark_asset="BTC",
    order_notional_min=10,
    fee_pct=0.00025,       # 2.5 bps per trade
    slippage_pct=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(metrics=metrics, returns=returns, output_path="tearsheet.html")

Metrics

Alphavec provides 53 comprehensive metrics across 8 categories:

Categories

  1. Meta (5 metrics): Simulation metadata and configuration
  2. Performance (6 metrics): Returns, volatility, Sharpe ratio, drawdowns
  3. Costs & Trading (5 metrics): Fees, funding, turnover, order statistics
  4. Exposure (6 metrics): Gross/net leverage metrics
  5. Benchmark (7 metrics): Alpha, beta, tracking error, information ratio (CAPM)
  6. Distribution (11 metrics): Win/loss stats, skewness, kurtosis, drawdown duration
  7. Portfolio (6 metrics): Holding periods, weights, cost ratios
  8. Risk (7 metrics): Sortino, VaR, CVaR, Omega, downside deviation, Ulcer Index

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.

New Risk Metrics (v0.2.0)

  • Sortino Ratio: Better than Sharpe for asymmetric returns (only penalizes downside)
  • VaR/CVaR: Industry-standard tail risk measures (95% confidence)
  • Omega Ratio: Comprehensive risk-adjusted return (all moments)
  • Gain-to-Pain: Simple efficiency metric
  • Ulcer Index: Drawdown-based risk that considers duration

Tearsheet Example

Tearsheet

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

alphavec-0.2.0.tar.gz (21.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

alphavec-0.2.0-py3-none-any.whl (17.3 kB view details)

Uploaded Python 3

File details

Details for the file alphavec-0.2.0.tar.gz.

File metadata

  • Download URL: alphavec-0.2.0.tar.gz
  • Upload date:
  • Size: 21.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for alphavec-0.2.0.tar.gz
Algorithm Hash digest
SHA256 3c56ce7b9605f4b9eb86508dc19909d7fe585bfe02e5332dfc01d632706d9902
MD5 f99ffba7a0e7ee53a193f74e39961961
BLAKE2b-256 1a6b7f02ba0a0ec96bf8f2adea1e217b865f37a17ec4e0ecf9881113b0c0a99e

See more details on using hashes here.

Provenance

The following attestation bundles were made for alphavec-0.2.0.tar.gz:

Publisher: python-publish.yml on breaded-xyz/alphavec

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file alphavec-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: alphavec-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 17.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for alphavec-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 a93bcd5b962caa42314408d28af92b1e13ea6ad814c303a1e657adc18e534568
MD5 2759704137b9c14e2b47ad6503228e78
BLAKE2b-256 6d3cd56a93b2147657a1bc82c192465b129f7331314dbfdcd759bef1a2b059d5

See more details on using hashes here.

Provenance

The following attestation bundles were made for alphavec-0.2.0-py3-none-any.whl:

Publisher: python-publish.yml on breaded-xyz/alphavec

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page