Skip to main content

Alpha Library: A high-performance rolling window calculation library implemented in Rust with Python bindings. Used for financial data analysis and factor research.

Project description

alpha-lib

High-performance quantitative finance algorithm library, implemented in Rust with Python bindings (PyO3).

Provides efficient rolling-window calculations commonly used in factor-based quantitative trading.

Performance

Benchmarked on Alpha 101, 4000 stocks x 261 trading days (1,044,000 data points per factor):

Implementation Factors Data Load Compute Total Speedup
pandas 75 31.2s 2,643s 2,675s (44min) 1x
polars_ta 81 0.3s 58s 58s 46x
alpha-lib 101 0.3s 3.6s 3.9s 729x

See COMPARISON.md for per-factor timing and correctness analysis.

Installation

pip install py-alpha-lib

Usage

Context Settings

Control computation behavior via alpha.set_ctx():

  • groups — Number of securities in the data array. Each group is processed independently and in parallel. Required for cross-sectional operations like RANK.

  • start — Starting index for calculation (default: 0).

  • end — Ending index for calculation (default: len(data)). end can be used when you want to calculate only a part of the data. for example, when back test iteratively.

  • flags — Bitwise flags:

    • FLAG_SKIP_NAN (1): Skip NaN values in rolling windows.
    • FLAG_STRICTLY_CYCLE (2): Return NaN until window is full (matches pandas rolling() default).
    • Combine with |: flags=FLAG_SKIP_NAN | FLAG_STRICTLY_CYCLE
    import alpha
    import numpy as np
    
    data = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=np.float64)
    
    # 3-period moving average (partial results during warm-up)
    result = alpha.MA(data, 3)
    # [1.  1.5 2.  3.  4.  5.  6.  7.  8.  9.]
    
    # Strict mode: NaN until window is full
    alpha.set_ctx(flags=alpha.FLAG_STRICTLY_CYCLE)
    result = alpha.MA(data, 3)
    # [nan nan 2.  3.  4.  5.  6.  7.  8.  9.]
    
    # Skip NaN values
    alpha.set_ctx(flags=alpha.FLAG_SKIP_NAN)
    data_nan = np.array([1, 2, np.nan, 4, 5, 6, 7, 8, 9, 10], dtype=np.float64)
    result = alpha.MA(data_nan, 3)
    #[1.    1.5     nan 2.333 3.667 5.    6.    7.    8.    9.   ]
    

Example 1: Plug and Play

import alpha
from alpha.context import ExecContext

# ExecContext auto-infers groups from securityid/tradetime columns
# and calls alpha.set_ctx(groups=...) automatically
data = pl.read_csv("data.csv").sort(["securityid", "tradetime"])
ctx = ExecContext(data)

# Call operators directly on numpy arrays
close = data["close"].to_numpy()
ma20 = alpha.MA(close, 20)
rank = alpha.RANK(close)       # cross-sectional rank (groups auto-configured)
corr = alpha.CORR(close, data["vol"].to_numpy().astype(float), 10)

Data layout: flat 1D array [stock1_day1, stock1_day2, ..., stockN_dayM], sorted by security then time. The groups parameter tells the library where each stock's data begins.

Example 2: Factor Expression Transpiler

Convert factor expressions to Python code, then run:

python -m alpha.lang examples/wq101/alpha101.txt
# 3. Use generated code
from alpha.context import ExecContext
from factors import alpha_001

data = pl.read_csv("data.csv").sort(["securityid", "tradetime"])
ctx = ExecContext(data)  # auto-infers groups
result = alpha_001(ctx)

Factor expression to Python code

You can convert factor expressions to Python code using the lang module. For example:

python -m alpha.lang examples/wq101/alpha101.txt

This will read the factor expressions from examples/wq101/alpha101.txt and generate corresponding Python code using alpha-lib functions.

After generating the code, you may need to adjust the code

  • Fix type conversions between float and bool.
  • Add context settings if needed.

Benchmarking and Full Examples

GTJA Alpha 191

Implementation of 190/191 factors from the GTJA (国泰君安) Alpha 191 factor set in examples/gtja191/:

Metric Value
Computable 190 / 191
Compute time ~4.5s (4000 stocks × 261 days)
Avg per factor 24ms
python -m examples.gtja191.al 143     # run specific factor
python -m examples.gtja191.al          # run all factors

WorldQuant Alpha 101

Full implementation of 101 Formulaic Alphas in examples/wq101/:

  • al/ — alpha-lib implementation (Rust backend)
  • pd_/ — pandas reference (DolphinDB port)
  • pl_/ — polars_ta reference
examples/wq101/main.py --with-al 1 2 3 4 # Run specific factors
examples/wq101/main.py --with-al -s 1 -e 102 # Run all factors
examples/wq101/main.py --with-pd --with-al -s 1 -e 15 # Compare with pandas

Benchmark scripts in benchmarks/.

Supported Algorithms

Naming Rules:

  • Function starts with CC_ means it is a cross-commodity/cross-security/cross-group operation.
  • Function without prefix means it is a rolling window operation.
Name Description
ALPHA Rolling Jensen's Alpha of asset returns against benchmark returns.
BACKFILL Forward-fill NaN values with the last valid observation
BARSLAST Calculate number of bars since last condition true
BARSSINCE Calculate number of bars since first condition true
BETA Rolling Beta coefficient of asset returns against benchmark returns.
BINS Discretize the input into n bins, the ctx.groups() is the number of groups
CC_RANK Calculate rank percentage cross group dimension, the ctx.groups() is the number of groups Same value are averaged
CC_ZSCORE Calculate cross-sectional Z-Score across groups at each time step
CORR Time Series Correlation in moving window on self
CORR2 Calculate two series correlation over a moving window
COUNT Calculate number of periods where condition is true in passed periods window
COUNT_NANS Count number of NaN values in a rolling window
COV Calculate Covariance over a moving window
CROSS For 2 arrays A and B, return true if A[i-1] < B[i-1] and A[i] >= B[i] alias: golden_cross, cross_ge
DMA Exponential Moving Average current = weight * current + (1 - weight) * previous
EMA Exponential Moving Average (variant of well-known EMA) weight = 2 / (n + 1)
ENTROPY Calculate rolling Shannon entropy over a moving window
FRET Future Return
GROUP_RANK Calculate rank percentage within each category group at each time step
GROUP_ZSCORE Calculate Z-Score within each category group at each time step
HHV Find highest value in a preceding periods window
HHVBARS The number of periods that have passed since the array reached its periods period high
INTERCEPT Linear Regression Intercept
KURTOSIS Calculate rolling sample excess Kurtosis over a moving window
LLV Find lowest value in a preceding periods window
LLVBARS The number of periods that have passed since the array reached its periods period low
LONGCROSS For 2 arrays A and B, return true if previous N periods A < B, Current A >= B
LWMA Linear Weighted Moving Average
MA Simple Moving Average, also known as arithmetic moving average
MAX_DRAWDOWN Rolling Maximum Drawdown.
MIN_MAX_DIFF Calculate rolling min-max difference (range) over a moving window
MOMENT Calculate rolling k-th central moment over a moving window
NEUTRALIZE Neutralize the effect of a categorical variable on a numeric variable
PRODUCT Calculate product of values in preceding periods window
QUANTILE Calculate rolling quantile over a moving window
RANK Calculate rank in a sliding window with size periods
RCROSS For 2 arrays A and B, return true if A[i-1] > B[i-1] and A[i] <= B[i] alias: death_cross, cross_le
REF Right shift input array by periods, r[i] = input[i - periods]
REGBETA Calculate Regression Coefficient (Beta) of Y on X over a moving window
REGRESI Calculate Regression Residual of Y on X over a moving window
RLONGCROSS For 2 arrays A and B, return true if previous N periods A > B, Current A <= B
SCAN_ADD Conditional cumulative add: r[t] = r[t-1] + (cond[t] ? input[t] : 0)
SCAN_MUL Conditional cumulative multiply: r[t] = r[t-1] * (cond[t] ? input[t] : 1)
SHARPE Rolling Sharpe Ratio of returns.
SKEWNESS Calculate rolling sample Skewness over a moving window
SLOPE Linear Regression Slope
SMA Exponential Moving Average (variant of well-known EMA) weight = m / n
STDDEV Calculate Standard Deviation over a moving window
SUM Calculate sum of values in preceding periods window
SUMBARS Calculate number of periods (bars) backwards until the sum of values is greater than or equal to amount
SUMIF Calculate sum of values in preceding periods window where condition is true
VAR Calculate Variance over a moving window
WEIGHTED_DELAY Calculate weighted delay (exponentially weighted lag)
ZSCORE Calculate rolling Z-Score over a moving window

Full function signatures: python/alpha/algo.md

Development

Requirements:

  • Rust (latest stable)
  • Python 3.11+
  • maturin
# Build and install in development mode
maturin develop --release

# Run tests
cargo test

Vibe Coding

When adding new algorithms with LLM assistance, provide the function list as context. Use the skill add_algo.md for guided implementation.

This project is a co-created by Gemini (through Antigravity) and Claude (from tic-top).

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

py_alpha_lib-0.2.4.tar.gz (175.8 kB view details)

Uploaded Source

Built Distributions

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

py_alpha_lib-0.2.4-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl (1.2 MB view details)

Uploaded PyPymusllinux: musl 1.2+ x86-64

py_alpha_lib-0.2.4-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (944.1 kB view details)

Uploaded PyPymanylinux: glibc 2.17+ x86-64

py_alpha_lib-0.2.4-cp314-cp314t-musllinux_1_2_x86_64.whl (1.2 MB view details)

Uploaded CPython 3.14tmusllinux: musl 1.2+ x86-64

py_alpha_lib-0.2.4-cp314-abi3-win_amd64.whl (885.5 kB view details)

Uploaded CPython 3.14+Windows x86-64

py_alpha_lib-0.2.4-cp313-cp313t-musllinux_1_2_x86_64.whl (1.2 MB view details)

Uploaded CPython 3.13tmusllinux: musl 1.2+ x86-64

py_alpha_lib-0.2.4-cp311-abi3-musllinux_1_2_x86_64.whl (1.2 MB view details)

Uploaded CPython 3.11+musllinux: musl 1.2+ x86-64

py_alpha_lib-0.2.4-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (943.3 kB view details)

Uploaded CPython 3.11+manylinux: glibc 2.17+ x86-64

py_alpha_lib-0.2.4-cp311-abi3-macosx_11_0_arm64.whl (869.2 kB view details)

Uploaded CPython 3.11+macOS 11.0+ ARM64

File details

Details for the file py_alpha_lib-0.2.4.tar.gz.

File metadata

  • Download URL: py_alpha_lib-0.2.4.tar.gz
  • Upload date:
  • Size: 175.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for py_alpha_lib-0.2.4.tar.gz
Algorithm Hash digest
SHA256 f9e4e9d92913ff5f5ba6776b690e637b4d1674ee8d77ef16f0abac3e98a1c02d
MD5 ce939f7c80a571760e579ba6867717a3
BLAKE2b-256 83b5f453cf5543d8534989f9dfe1ff76243513c0056cbf4b279a3f416384a16c

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.2.4.tar.gz:

Publisher: CI.yml on msd-rs/py-alpha-lib

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

File details

Details for the file py_alpha_lib-0.2.4-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl.

File metadata

File hashes

Hashes for py_alpha_lib-0.2.4-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 cbb7bf0bb407c19378d43503c153ceb575fc04c72c4d42bc0f276734ec181bf0
MD5 3cc68b5f0c9e85b88379945b6404139e
BLAKE2b-256 277bfbb3dffe3202b488971eaa84d9648aa06f25fbee32ec11f870e93bcc0792

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.2.4-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl:

Publisher: CI.yml on msd-rs/py-alpha-lib

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

File details

Details for the file py_alpha_lib-0.2.4-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for py_alpha_lib-0.2.4-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 6c8e16ff1157ddd61ffb459563d172770101d35eb8fc14ea876dbe21e18cafb9
MD5 5905de75f12114d309a821a2006df7c1
BLAKE2b-256 3496e923558fd1878ec6e799140c7a4fad4a02adc0880b05563c253130669338

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.2.4-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl:

Publisher: CI.yml on msd-rs/py-alpha-lib

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

File details

Details for the file py_alpha_lib-0.2.4-cp314-cp314t-musllinux_1_2_x86_64.whl.

File metadata

File hashes

Hashes for py_alpha_lib-0.2.4-cp314-cp314t-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 3a922e5a88b8cfddb95f27e095aa04f082eb59986ecb6a12647e01ed6914cc5c
MD5 c02012986ded66387e8f6a74cf2b6dd9
BLAKE2b-256 a8b260dc72259b0883b4ca1af8a492615787a7a456c947788a25a73c693128a6

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.2.4-cp314-cp314t-musllinux_1_2_x86_64.whl:

Publisher: CI.yml on msd-rs/py-alpha-lib

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

File details

Details for the file py_alpha_lib-0.2.4-cp314-abi3-win_amd64.whl.

File metadata

  • Download URL: py_alpha_lib-0.2.4-cp314-abi3-win_amd64.whl
  • Upload date:
  • Size: 885.5 kB
  • Tags: CPython 3.14+, Windows x86-64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for py_alpha_lib-0.2.4-cp314-abi3-win_amd64.whl
Algorithm Hash digest
SHA256 36c7dd2c425b32fd5f2051c73a5ab32f6e6ecaca82a5e584832345c1bb944a36
MD5 b724ea6f8b2c4d1f24f391d9e876204b
BLAKE2b-256 8b3981c42946d89b2e23decd7d19ddb3ee1eceb9e2b068914c94a9d18281353c

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.2.4-cp314-abi3-win_amd64.whl:

Publisher: CI.yml on msd-rs/py-alpha-lib

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

File details

Details for the file py_alpha_lib-0.2.4-cp313-cp313t-musllinux_1_2_x86_64.whl.

File metadata

File hashes

Hashes for py_alpha_lib-0.2.4-cp313-cp313t-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 4eb50e62669a55a57fcbcc3ea90e831d08e832d87ae1058676f8901e7ad48477
MD5 8360d70ccd4b23f929b7fd980da705f7
BLAKE2b-256 2c759caf9afff053f75f600f5ecb47081111f2fb39ad0e7b2ed7232696eb515f

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.2.4-cp313-cp313t-musllinux_1_2_x86_64.whl:

Publisher: CI.yml on msd-rs/py-alpha-lib

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

File details

Details for the file py_alpha_lib-0.2.4-cp311-abi3-musllinux_1_2_x86_64.whl.

File metadata

File hashes

Hashes for py_alpha_lib-0.2.4-cp311-abi3-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 3f5b199007f657acd895cf864c91eba8c3ffc5bd9c02e42546e59afe8af963fc
MD5 7a510e17032f839efdae69fbed29dda5
BLAKE2b-256 e838c31c08a4a0c7ba5222405ac4617c146651d1d46fefbfdb2bffab4f6038f6

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.2.4-cp311-abi3-musllinux_1_2_x86_64.whl:

Publisher: CI.yml on msd-rs/py-alpha-lib

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

File details

Details for the file py_alpha_lib-0.2.4-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for py_alpha_lib-0.2.4-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 ea9c9b87d29c52b9a55eee321c6755467068de3dcd6f6e2fba157dd22f7cf481
MD5 62c0475f3dfa175526962087f57b06b1
BLAKE2b-256 5151c5577a7079367a69355906fd63153a80f1eb74460c02542f567b424a70b2

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.2.4-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl:

Publisher: CI.yml on msd-rs/py-alpha-lib

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

File details

Details for the file py_alpha_lib-0.2.4-cp311-abi3-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for py_alpha_lib-0.2.4-cp311-abi3-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 97092395bf89a3897e6dd47f3d14db2ab558213535c54ceac565d337f607448d
MD5 f2faf34994a4146abb02145f9b075dd4
BLAKE2b-256 72507d7a843e3e45b2fbdc8f8cf86555bf0755f9a59ad0d34179672e545561d1

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.2.4-cp311-abi3-macosx_11_0_arm64.whl:

Publisher: CI.yml on msd-rs/py-alpha-lib

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