Skip to main content

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
BW_SPLIT Backward split and dividend adjustment
BW_SPLIT_FACTOR Backward split factor calculation
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
CC_WINSORIZE_MAD Cross-sectional MAD winsorization across groups at each time step. Clips finite values in each cross-section to [median - 1.4826 * mad_k * MAD, median + 1.4826 * mad_k * MAD]. Zero-MAD cross-sections (1.4826 * mad_k * MAD <= 1e-12) preserve finite values unchanged. Non-finite inputs (NaN/Inf) produce NaN output.
CC_WINSORIZE_PCT Cross-sectional percentile winsorization across groups at each time step. Clips finite values in each cross-section to the linear-interpolated [pct_low, pct_high] quantiles (0.0 <= pct_low < pct_high <= 1.0). Non-finite inputs (NaN/Inf) produce NaN output.
CC_WINSORIZE_SIGMA Cross-sectional standard-deviation (sigma) winsorization across groups at each time step. Clips finite values in each cross-section to [mean - sigma_k * std, mean + sigma_k * std] using population standard deviation (ddof = 0). Degenerate cross-sections (cnt <= 1 or std <= 1e-12) preserve finite values unchanged. Non-finite inputs produce NaN.
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
FW_SPLIT Forward split and dividend adjustment
FW_SPLIT_FACTOR Forward split factor calculation
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

Other language bindings

This project is Python based originally, but for some case Python is not available, for example

  • You build a stock web app, you want draw an indicator on the chart.
  • Your application will be deployed to customer's computer, it is not easy to install Python on the customer's computer. But lua can be embeded in your app.

So we add some other language bindings for this project.

  • lua-binding: Provide a UserData named NumArray to do numpy.ndarray like operations, and register all ta funtions to lua. So you can use it in your lua application.
  • js-binding: Provide a MLang runtime to execute mlang code on the browser. And use canvas to draw the chart.

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).

Metadata

Release files for py-alpha-lib 0.5.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for py-alpha-lib 0.5.3
File Size Uploaded Provenance Actions
py_alpha_lib-0.5.3.tar.gz 330.7 kB With provenance Details for py_alpha_lib-0.5.3.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for py-alpha-lib 0.5.3
File Actions
py_alpha_lib-0.5.3-cp315-abi3.abi3t-win_amd64.whl CPython 3.15 abi3, abi3t Windows x86-64 Details for py_alpha_lib-0.5.3-cp315-abi3.abi3t-win_amd64.whl
py_alpha_lib-0.5.3-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl CPython 3.15 abi3, abi3t Linux musl 1.2+ x86-64 Details for py_alpha_lib-0.5.3-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl
py_alpha_lib-0.5.3-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl CPython 3.15 abi3, abi3t Linux glibc 2.17+ x86-64 Details for py_alpha_lib-0.5.3-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
py_alpha_lib-0.5.3-cp315-abi3.abi3t-macosx_11_0_arm64.whl CPython 3.15 abi3, abi3t macOS 11.0+ ARM64 Details for py_alpha_lib-0.5.3-cp315-abi3.abi3t-macosx_11_0_arm64.whl
py_alpha_lib-0.5.3-cp312-abi3-win_amd64.whl CPython 3.12 abi3 Windows x86-64 Details for py_alpha_lib-0.5.3-cp312-abi3-win_amd64.whl
py_alpha_lib-0.5.3-cp312-abi3-musllinux_1_2_x86_64.whl CPython 3.12 abi3 Linux musl 1.2+ x86-64 Details for py_alpha_lib-0.5.3-cp312-abi3-musllinux_1_2_x86_64.whl
py_alpha_lib-0.5.3-cp312-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl CPython 3.12 abi3 Linux glibc 2.17+ x86-64 Details for py_alpha_lib-0.5.3-cp312-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
py_alpha_lib-0.5.3-cp312-abi3-macosx_11_0_arm64.whl CPython 3.12 abi3 macOS 11.0+ ARM64 Details for py_alpha_lib-0.5.3-cp312-abi3-macosx_11_0_arm64.whl

Total release size: 12.4 MB

Release files / py_alpha_lib-0.5.3.tar.gz

Download URL py_alpha_lib-0.5.3.tar.gz
Size 330.7 kB
Tags Source
SHA-256 checksum
How to use checksums
a48844fac52959ee9855cc4af90e72f2eb9e6beccf14301a6344effcc312973f
BLAKE2b-256 checksum
How to use checksums
3b495f303e438810f8178e0aa8780acd14c3b39c0672bf7cf113d9ff47d537b3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / py_alpha_lib-0.5.3-cp315-abi3.abi3t-win_amd64.whl

Download URL py_alpha_lib-0.5.3-cp315-abi3.abi3t-win_amd64.whl
Size 1.5 MB
Tags CPython 3.15 Windows x86-64 abi3 abi3t
SHA-256 checksum
How to use checksums
c8415093c62451a1c1e616a00ac780ab6d81f80300a5df2c06aaea02a8b98ca0
BLAKE2b-256 checksum
How to use checksums
61ea68849607404606160e57bb1ab503dd017b728e41e591d0da33b23c8d8038
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / py_alpha_lib-0.5.3-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl

Download URL py_alpha_lib-0.5.3-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl
Size 1.8 MB
Tags CPython 3.15 Linux musl 1.2+ x86-64 abi3 abi3t
SHA-256 checksum
How to use checksums
e77de5d057cb62fabc7748d6aa03661ac616032b9afc4e7219eb4befb509e455
BLAKE2b-256 checksum
How to use checksums
3ee1b41a6847d763c68d27fd2976e9b3b7e091e4d994198ef6c816ea74e8731f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / py_alpha_lib-0.5.3-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl

Download URL py_alpha_lib-0.5.3-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Size 1.4 MB
Tags CPython 3.15 Linux glibc 2.17+ x86-64 abi3 abi3t
SHA-256 checksum
How to use checksums
c942dc160675e5eedd28be4570908b5d3e8dce5af055e2640b67e41fd88a5e51
BLAKE2b-256 checksum
How to use checksums
febe6c6cee9d965ebb218a15ca31a299e280c0b7afd32ebeeb7ace895819a8c3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / py_alpha_lib-0.5.3-cp315-abi3.abi3t-macosx_11_0_arm64.whl

Download URL py_alpha_lib-0.5.3-cp315-abi3.abi3t-macosx_11_0_arm64.whl
Size 1.3 MB
Tags CPython 3.15 abi3 abi3t macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
44c5753f59aeea6b5b000a46befa02cd9585e3baf23285a1c9fa629a9632786c
BLAKE2b-256 checksum
How to use checksums
ac15b2d2b6d34d85861f6b36fafcc77df427cf39644fb05a87b14fafefb528f0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / py_alpha_lib-0.5.3-cp312-abi3-win_amd64.whl

Download URL py_alpha_lib-0.5.3-cp312-abi3-win_amd64.whl
Size 1.5 MB
Tags CPython 3.12 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
cfca08c7c23ead2625f37bb08ae8e1e127db6799ddf7fef938a6ed80b3874e7a
BLAKE2b-256 checksum
How to use checksums
8365df449708045978cfabd043a0efd2dac7299388bc4f65f39695581c8b8ed0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / py_alpha_lib-0.5.3-cp312-abi3-musllinux_1_2_x86_64.whl

Download URL py_alpha_lib-0.5.3-cp312-abi3-musllinux_1_2_x86_64.whl
Size 1.8 MB
Tags CPython 3.12 Linux musl 1.2+ x86-64 abi3
SHA-256 checksum
How to use checksums
4062ad469b6872869d110f9b10d671f691314002477ead6aa96ac7df1b5e43c4
BLAKE2b-256 checksum
How to use checksums
da907309064e4d3be7ac68aff27ede21658f8c891f9a578002c9366cb6bdc022
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / py_alpha_lib-0.5.3-cp312-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl

Download URL py_alpha_lib-0.5.3-cp312-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Size 1.4 MB
Tags CPython 3.12 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
bc1c19607677e3349d5702b3d9df4ab08915393463ebf57ef65f556726f4f266
BLAKE2b-256 checksum
How to use checksums
e38d8233b96aec9df5a0ff3065f4bab3a1b29d7f4d0dee7737876ba63b5a3902
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / py_alpha_lib-0.5.3-cp312-abi3-macosx_11_0_arm64.whl

Download URL py_alpha_lib-0.5.3-cp312-abi3-macosx_11_0_arm64.whl
Size 1.3 MB
Tags CPython 3.12 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
268a96cafabde71c1fa309405da3b616796320d3fcc126d3a68fac2dd5e6a1c8
BLAKE2b-256 checksum
How to use checksums
6abf3614d054198d090dc208f9c7d966fb78da44cec960c0787d3363a3851b14
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Security for py-alpha-lib 0.5.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 9 files in this release have been uploaded with provenance metadata.

Select from 9 files

Attestation for py_alpha_lib-0.5.3.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page