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

  • 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 3.  4.5 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

Name Description
BARSLAST Bars since last condition true
BARSSINCE Bars since first condition true
BINS Discretize input into n bins
CORR Rolling correlation
COUNT Count of true values in window
COV Rolling covariance
CROSS Golden cross detection (A crosses above B)
DMA Exponential moving average (custom weight)
EMA Exponential moving average (weight = 2/(n+1))
FRET Future return calculation
GROUP_RANK Rank percentage within category group
GROUP_ZSCORE Z-score within category group
HHV / LLV Highest / lowest value in window
HHVBARS / LLVBARS Bars since highest / lowest value
INTERCEPT Linear regression intercept
LONGCROSS A < B for N periods then A >= B
LWMA Linear weighted moving average
MA Simple moving average
NEUTRALIZE Neutralize categorical effect
PRODUCT Rolling product
RANK Cross-sectional rank (percentage)
RCROSS Death cross detection (A crosses below B)
REF Shift array by N periods
REGBETA Regression coefficient (beta)
REGRESI Regression residual
RLONGCROSS A > B for N periods then A <= B
SCAN_ADD Conditional cumulative sum (SELF recursion)
SCAN_MUL Conditional cumulative product (SELF recursion)
SLOPE Linear regression slope
SMA EMA variant (weight = m/n)
STDDEV Rolling standard deviation
SUM Rolling sum (0 = cumulative)
SUMBARS Bars until sum reaches threshold
SUMIF Conditional rolling sum
TS_BACKFILL Forward-fill NaN with last valid value
TS_CORR Time series correlation
TS_COUNT_NANS Rolling count of NaN values in window
TS_ENTROPY Rolling Shannon entropy over binned window
TS_KURTOSIS Rolling excess kurtosis (Fisher-adjusted)
TS_MIN_MAX_DIFF Rolling range (max - min) over window
TS_MOMENT Rolling k-th central moment
TS_RANK Rank within sliding window
TS_SKEWNESS Rolling skewness (Fisher-Pearson adjusted)
TS_WEIGHTED_DELAY Exponentially weighted lag (LWMA of lagged series)
TS_ZSCORE Rolling z-score over window
VAR Rolling variance
ZSCORE Cross-sectional z-score

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.1.3.tar.gz (167.9 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.1.3-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl (1.1 MB view details)

Uploaded PyPymusllinux: musl 1.2+ x86-64

py_alpha_lib-0.1.3-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (900.4 kB view details)

Uploaded PyPymanylinux: glibc 2.17+ x86-64

py_alpha_lib-0.1.3-cp314-cp314t-musllinux_1_2_x86_64.whl (1.1 MB view details)

Uploaded CPython 3.14tmusllinux: musl 1.2+ x86-64

py_alpha_lib-0.1.3-cp314-abi3-win_amd64.whl (814.4 kB view details)

Uploaded CPython 3.14+Windows x86-64

py_alpha_lib-0.1.3-cp313-cp313t-musllinux_1_2_x86_64.whl (1.1 MB view details)

Uploaded CPython 3.13tmusllinux: musl 1.2+ x86-64

py_alpha_lib-0.1.3-cp311-abi3-musllinux_1_2_x86_64.whl (1.1 MB view details)

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

py_alpha_lib-0.1.3-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (900.4 kB view details)

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

py_alpha_lib-0.1.3-cp311-abi3-macosx_11_0_arm64.whl (824.5 kB view details)

Uploaded CPython 3.11+macOS 11.0+ ARM64

File details

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

File metadata

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

File hashes

Hashes for py_alpha_lib-0.1.3.tar.gz
Algorithm Hash digest
SHA256 b0cfa90c58fc211e64882c16e5530666a346ed8f5a2c26bcf9ba598c58b2150a
MD5 1cb56d4926ea7d957f62b78127e4d386
BLAKE2b-256 653ffe53e39fe95dec307af26fdc261ea29e565e631eed547538caa9330d2e0a

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for py_alpha_lib-0.1.3-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 fc9ec38c61577787b1bcc60448d364658223e8d1415852b6d7a3af0333c6b8ea
MD5 b5c0ec7e4e7750edf32ff080d3059784
BLAKE2b-256 45beb94394361449d3b99e999886f14dd687da025b2a2413471d19842c7f4bec

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for py_alpha_lib-0.1.3-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 9ddd905183f6c8a1bef08a8b47ea33cde986d81cab3ef4a2e6f71d82682a1987
MD5 214dcc0fffdbf3acaa2958e4a8172544
BLAKE2b-256 ca1c3cad3e494bc3a8f710e6dc3f4dd67ce2f69a8acc7bbc72c78edbcb9f0efc

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.1.3-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.1.3-cp314-cp314t-musllinux_1_2_x86_64.whl.

File metadata

File hashes

Hashes for py_alpha_lib-0.1.3-cp314-cp314t-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 9b85b57d5ab515b26b00cde80b34b25d104e7603170580ebfb2de36314fca103
MD5 9d3f57e1ef90c9db8f4bc2289b333b4d
BLAKE2b-256 305d834149bbbef116001bd90384f07239c8d0b7b776a0b6f7f2fdb67baa56e6

See more details on using hashes here.

Provenance

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

File metadata

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

File hashes

Hashes for py_alpha_lib-0.1.3-cp314-abi3-win_amd64.whl
Algorithm Hash digest
SHA256 f9d82555ef0de9957d065c7a27bb559b200850fe3ef04d0f14a0a55de36e0f27
MD5 f75b141b05eacde4a6a56e53f20aa9c4
BLAKE2b-256 36620f82fd160d7e4872655fe513080a3fe778682a7760569f3393b04b865c9b

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_alpha_lib-0.1.3-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.1.3-cp313-cp313t-musllinux_1_2_x86_64.whl.

File metadata

File hashes

Hashes for py_alpha_lib-0.1.3-cp313-cp313t-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 1fbc92ec7d042e10dff577238cade2d1c67f258e47da99af62a3cce8d68ec86f
MD5 869bbd99f3c922e35a35b794e0832cdd
BLAKE2b-256 e31c96bc84b6276f9367aecc3c0949772b8cfd0827ae78718b71bc2de0a17a64

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for py_alpha_lib-0.1.3-cp311-abi3-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 3ed54714ba5f168ee7d34cf117aaf77bf4ee427150419ffc18420f4752677472
MD5 c6b05f4a941bd2322f7a011ce3df9228
BLAKE2b-256 69bc3e4b65e74eb244c294a003e4df5831f7141f813aea334d33df27ea742312

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for py_alpha_lib-0.1.3-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 66a84c9942fad65e634246ab5e8f889f070426bc3e2dcc9b5bd26d810164cfba
MD5 6f0729fb06baa07f09adc28cac55b61d
BLAKE2b-256 8ceda2f23c3bca85102d302ee0febe9fd212fdd960231f74bc0735cfc40d0dfa

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for py_alpha_lib-0.1.3-cp311-abi3-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 e00c219496b99c882b8c091509980e485988f15cb2a4005be078a5190df32689
MD5 02befd4784482495018ace7a73439c96
BLAKE2b-256 fb9ef3ea0f8eeb2279eab2b7245194c90aa5335dabc172ac6f9d5b41e59819d2

See more details on using hashes here.

Provenance

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