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

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

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.3.0.tar.gz (174.7 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.3.0-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.3.0-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (963.9 kB view details)

Uploaded PyPymanylinux: glibc 2.17+ x86-64

py_alpha_lib-0.3.0-cp315-cp315t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (952.5 kB view details)

Uploaded CPython 3.15tmanylinux: glibc 2.17+ x86-64

py_alpha_lib-0.3.0-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.3.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (952.3 kB view details)

Uploaded CPython 3.14tmanylinux: glibc 2.17+ x86-64

py_alpha_lib-0.3.0-cp314-abi3-win_amd64.whl (910.2 kB view details)

Uploaded CPython 3.14+Windows x86-64

py_alpha_lib-0.3.0-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.3.0-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (963.1 kB view details)

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

py_alpha_lib-0.3.0-cp311-abi3-macosx_11_0_arm64.whl (887.9 kB view details)

Uploaded CPython 3.11+macOS 11.0+ ARM64

File details

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

File metadata

  • Download URL: py_alpha_lib-0.3.0.tar.gz
  • Upload date:
  • Size: 174.7 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.3.0.tar.gz
Algorithm Hash digest
SHA256 1e7434f1416ed035da195c81a1fd82994ca4c98f5f4b4dcf759d941311accb6f
MD5 80cd08cdc8a40af6e52b5bd5fa41218b
BLAKE2b-256 0769a43d47655ef60d46d3fff2c72edc04c0f1601b179b65fdf58a8dd7a7df5f

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.3.0.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.3.0-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl.

File metadata

File hashes

Hashes for py_alpha_lib-0.3.0-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 5569d03a4117ca54cbef1a9038b019ae7a91d5529b4bb24c79d696e1e79c733c
MD5 1f5e90f6d07d2056f5a72bec72d74352
BLAKE2b-256 0d0188d92c783b2db74a46c7258d82f431ac77d9ce5e33fc04a4e56ac3d3eeba

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.3.0-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.3.0-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for py_alpha_lib-0.3.0-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 2ad08822bb2b95251d297b376e1468ad6908be654d6bcfe023cfdae4a142d535
MD5 48361e9dc147c6d16c70042f6a07b654
BLAKE2b-256 d769f35934093cf31c842841c0ebc3ccdfef5477d088b6d0975ab7ea12dd04b8

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.3.0-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.3.0-cp315-cp315t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for py_alpha_lib-0.3.0-cp315-cp315t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 12462f3737234ea5ba6402637672bd26caa11dcacf765ea0ec33b508456d46ea
MD5 8884fc41d92fb5f276cc956661d4fe36
BLAKE2b-256 83242211b337d1370d525916a8ecc06a92eedf57a217c98ab3fb8ac51a44fa60

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.3.0-cp315-cp315t-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.3.0-cp314-cp314t-musllinux_1_2_x86_64.whl.

File metadata

File hashes

Hashes for py_alpha_lib-0.3.0-cp314-cp314t-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 dbcc23203aa461012cdfcf19511052e98c6c28f08f88ed6ea7ce16e30007338f
MD5 68dddf9fd92f3d99c9de7f054b46f2e4
BLAKE2b-256 f7fe3e47f77ba8ec395817cfd4e22576e11fdf05a217b6faab6777206ef8a937

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.3.0-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.3.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for py_alpha_lib-0.3.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 fda1d90a77ee861ee6c2ae9a9ba084abd1b25bf93f92a1e7d96bce316486eece
MD5 49753cb6494acd49873b5588eb988e70
BLAKE2b-256 d34b6264d642671ec0555f2db81e151ee3d0507220fa962cec16a6af3fd735ba

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.3.0-cp314-cp314t-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.3.0-cp314-abi3-win_amd64.whl.

File metadata

  • Download URL: py_alpha_lib-0.3.0-cp314-abi3-win_amd64.whl
  • Upload date:
  • Size: 910.2 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.3.0-cp314-abi3-win_amd64.whl
Algorithm Hash digest
SHA256 eb34830c8b58ea1a33c0d2ce0b2837e55bfac03481acdc4bac54b2c36a440a0a
MD5 df34ffd92a1e3e22a8d34ea0c0058d4a
BLAKE2b-256 d42180016ef32eda75528cf8a212852c1889d9876612029bbf2c9f288e3a6df4

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.3.0-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.3.0-cp311-abi3-musllinux_1_2_x86_64.whl.

File metadata

File hashes

Hashes for py_alpha_lib-0.3.0-cp311-abi3-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 bc4b32ab0232dd5f9746ba74e95ea7c2a46666618aa99cae4f9d86e7fb8024a8
MD5 044d6d02bcf3e4813b71f9d6e8daea97
BLAKE2b-256 98c76566ba7906c7d5713e13ff98844ee89039eba38f9fc65e2ff250f075fc9d

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.3.0-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.3.0-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for py_alpha_lib-0.3.0-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 febe9c3cf290500b1a17988f57d200233512359753f5b1f02fcf6dae7dad3f3c
MD5 b4df539c5b01ac221ad6f252a2ee8029
BLAKE2b-256 2b1699fc95fb08edc0220e51c9a685cf885ab7bbfc2fe0a94d215a94ff94ac62

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.3.0-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.3.0-cp311-abi3-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for py_alpha_lib-0.3.0-cp311-abi3-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 244fc42854439bd494b4d0c2ff57caf694753dc3c53634d2e9456bd26e00bcc6
MD5 6be724a8c0a7b3b4a351e82bfd540288
BLAKE2b-256 ebbd37d7bfc1485bd2821453e3b342e89ad5814921ab2ee03052a851607610b6

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.3.0-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.

Release history Release notifications | RSS feed

0.3.1

10 files

This release

0.3.0 This release

10 files

0.2.5

9 files

0.2.4

9 files

0.2.3

9 files

0.2.2

9 files

0.2.1

9 files

0.2.0

9 files

0.1.3

9 files

0.1.2

9 files

0.1.1

9 files

0.1.0

9 files

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