Skip to main content

Building blocks for quantitative ML pipelines: technical features, preprocessing, feature selection, splitting and random-forest training.

Project description

quant-ml-toolkit

PyPI version Python versions License: MIT

A small Python toolkit for building quantitative machine-learning pipelines — from raw OHLCV price data through to a trained, explainable model.

The pieces are designed to chain together, but each is usable on its own:

raw OHLCV
   -> technical features        (TechnicalFeatureCalculator)
   -> cleaning & scaling        (FeaturePreprocessor)
   -> feature selection         (FeatureSelector)
   -> train / val / test split  (SampleSplit)
   -> model training + SHAP     (RandomForestModelTrainer)

Installation

pip install quant-ml-toolkit

The base install is lightweight. Two features need optional extras:

pip install "quant-ml-toolkit[talib]"   # technical features (needs the TA-Lib C library, see below)
pip install "quant-ml-toolkit[shap]"    # SHAP explanations
pip install "quant-ml-toolkit[all]"     # everything

TechnicalFeatureCalculator depends on TA-Lib, whose Python wrapper requires the underlying TA-Lib C library to be installed separately (e.g. brew install ta-lib, conda install -c conda-forge ta-lib, or your platform's package manager).

Requires Python 3.10–3.13.

Quick start

The examples assume price data pulled from Yahoo Finance via yfinance.

Note on yfinance columns. Recent versions of yfinance return a MultiIndex column layout by default (e.g. ('Close', 'AAPL')). TechnicalFeatureCalculator matches columns by the suffixes Open/High/Low/Close/Volume, so pass multi_level_index=False to get the flat columns it expects:

import yfinance as yf

ohlcv = yf.download(
    "AAPL", start="2018-01-01", end="2023-12-31",
    multi_level_index=False,   # -> flat Open/High/Low/Close/Volume columns
)

1. Compute technical features

from quant_ml_toolkit import TechnicalFeatureCalculator

calc = TechnicalFeatureCalculator(ohlcv)
features = calc.get_feature_df(
    technical_indicators_close=True,   # Return, ROC, RSI, volatility, Bollinger bands, ...
    technical_indicators_ohlc=True,    # ATR, CCI, Stochastic, ADX, Aroon, Williams %R, ...
    level_measures=True,               # SMA/EMA (10/20/50/200)
    volume_change=True,                # volume % change
    lag_close=True, lag_return=True,   # lagged close / return columns
)

You can also pass a single close-price Series instead of a DataFrame; in that case only the close-based indicators are computed.

2. Build a target and split

import numpy as np
from quant_ml_toolkit import SampleSplit

# example target: sign of next-day return (a simple up/down classification)
features["target"] = np.sign(ohlcv["Close"].pct_change().shift(-1))
data = features.dropna()

feature_cols = [c for c in data.columns if c != "target"]

# chronological split (shuffle=False by default — important for time series)
X_train, y_train, X_test, y_test = SampleSplit.TrainTestXYSplit(
    data, feature_variables=feature_cols, target_variables=["target"],
    train_size=80, test_size=20,
)

3. Preprocess (fit on train, apply to test)

from quant_ml_toolkit import FeaturePreprocessor

pp = FeaturePreprocessor(X_train, test_features_df=X_test)
pp.handle_missing_values()
pp.handle_infinity_values()
pp.handle_outlier_values_boundary_method(z_threshold=3)
pp.normalize(standardize=True)
X_train, X_test = pp.load_data()

All statistics (fill values, outlier bounds, the scaler) are fitted on the training set only and then applied to the test set, so there is no look-ahead leakage.

4. Select features

from quant_ml_toolkit import FeatureSelector

fs = FeatureSelector(X_train, X_test, y_train.squeeze(), model_type="Classification")
fs.remove_constant_features()
fs.remove_correlated_features(corr_thld=0.9)
fs.select_feature_by_mutual_information(select_k=20)
X_train, X_test = fs.X_train, fs.X_test

5. Train, tune and explain

from quant_ml_toolkit import RandomForestModelTrainer

trainer = RandomForestModelTrainer(
    X_train, X_test, y_train.squeeze(), y_test.squeeze(),
    model_type="classification",
)

# randomized hyperparameter search over a sensible default grid
trainer.fit(random_search=True, scoring="accuracy", n_iter=25, cv=3)

predictions = trainer.predict()

# feature importance via SHAP (requires the [shap] extra)
trainer.compute_shap_values()
importance = trainer.get_shap_values_df()      # mean |SHAP| per feature, sorted
trainer.shap_summary_plot(title="Feature importance").show()

Modules

Module Key API What it does
data to_period_timestamp, rolling_window, monthly_return_from_daily_close Date parsing, walk-forward in/out-of-sample windows, daily→monthly returns
features TechnicalFeatureCalculator Technical-indicator feature engineering (TA-Lib)
preprocessing FeaturePreprocessor, get_dummy_and_numerical_variables Leakage-safe missing/inf/outlier handling and scaling
selection FeatureSelector Constant/correlation/mutual-information/RFE/ROC-AUC selection
splitting SampleSplit Percentage-based train/val/test and X/y splits
modelling RandomForestModelTrainer Random-forest training, randomized search, SHAP

License

MIT

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

quant_ml_toolkit-0.2.0.tar.gz (23.7 kB view details)

Uploaded Source

Built Distribution

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

quant_ml_toolkit-0.2.0-py3-none-any.whl (21.4 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for quant_ml_toolkit-0.2.0.tar.gz
Algorithm Hash digest
SHA256 b3ad31e4bc2b72391599aeed6e9a7ecb38835eea5e7f99e513207eeb5f979df2
MD5 2d59fa1cfc09f38606eff8663fa034b3
BLAKE2b-256 c2b42d22d467a176a5d3c2212a38da71baaac3ab1082e09c430e2db826bd6670

See more details on using hashes here.

Provenance

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

Publisher: ci.yml on leoniedong/quant-ml-toolkit

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

File details

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

File metadata

File hashes

Hashes for quant_ml_toolkit-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 31e5101b59af651bf4f6f5f1bc1ee09aaea82b5ec8c8c3708e8ff81ea11ecba2
MD5 4fe02644d023e3c4c9fb0bf07bcc7ba5
BLAKE2b-256 3cc8fb126360da0601d37346613698d3219c14f637ad1aa9788e584a47f450f5

See more details on using hashes here.

Provenance

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

Publisher: ci.yml on leoniedong/quant-ml-toolkit

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