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

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_utils 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_utils 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_utils 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_utils 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_utils 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.1.0.tar.gz (21.1 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.1.0-py3-none-any.whl (21.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: quant_ml_toolkit-0.1.0.tar.gz
  • Upload date:
  • Size: 21.1 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.1.0.tar.gz
Algorithm Hash digest
SHA256 8b4ac8f5bb5a5df8a5992f0d64d38817c7d1d53c17544e88a7e2b8de58d9aae4
MD5 2515db42300bc3eeab7db8bf4fe59414
BLAKE2b-256 620ce59ddfaa4aa4f2cfcdbb1913dc3bc52e3141cc8b179f704747c589f5aac6

See more details on using hashes here.

Provenance

The following attestation bundles were made for quant_ml_toolkit-0.1.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.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for quant_ml_toolkit-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0d32b100b279bd301a58e65b55112342ab782afc29ba648d8f29fd89fc159e8c
MD5 08a095bd78e8305df9325c55a63d89e5
BLAKE2b-256 f7d17372368d05424d3d2b7fc34e20e8ca7bf9b5a0d610c1375825b4c6da262c

See more details on using hashes here.

Provenance

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