strategy

Machine Learning with a Voting Classifier

This template uses voting for combining classifiers and it shows how to use the backtester with retraining option.

You can clone and edit this example there (tab Examples).


With Quantiacs you can use machine learning methods for forecasting financial time series.

In this template we show how to use the Quantiacs toolkit for efficiently retraining your model on a rolling basis.

We will work with the BTC Futures Contracts and use voting on top of a combination of Ridge Classifiers and Stochastic Gradient Descent Classifiers as implemented in scikit-learn.

We will use a specialized version of the Quantiacs backtester for this purpose, which dramatically speeds up the backtesting process when the models should be retrained on a regular basis.

Need help? Check the Documentation and find solutions/report problems in the Forum section.

More help with Jupyter? Check the official Jupyter page.

Once you are done, click on Submit to the contest and take part to our competitions.

API reference:

  • data: check how to work with data;

  • backtesting: read how to run the simulation and check the results.

In [1]:
%%javascript
window.IPython && (IPython.OutputArea.prototype._should_scroll = function(lines) { return false; })
// disable widget scrolling
In [2]:
import logging

import pandas as pd
import xarray as xr
import numpy as np

import qnt.backtester as qnbt
import qnt.ta as qnta
In [3]:
def create_model():
    """This is a constructor for the ML model which can be easily modified using
       different models or another logic for the combination.
    """
    
    from sklearn.ensemble import VotingClassifier
    from sklearn.linear_model import SGDClassifier, RidgeClassifier
    import random
    
    # We will use a model obtained combining by voting Ridge Classifiers and SGD Classifiers
    # which use several random seeds to reduce overfitting:
    classifiers = []
    r = random.Random(13)
    for i in range(42):
        classifiers.append(('ridge' + str(i), RidgeClassifier(random_state=r.randint(0, pow(2, 32) - 1)),))
        classifiers.append(('sgd' + str(i), SGDClassifier(random_state=r.randint(0, pow(2, 32) - 1)),))
    model = VotingClassifier(classifiers)

    return model
In [4]:
def get_features(data):
    """Builds the features used for learning:
       * a trend indicator;
       * the stochastic oscillator;
       * volatility;
       * volume.
    """
    
    trend = qnta.roc(qnta.lwma(data.sel(field='close'), 70), 1)

    # stochastic oscillator:
    k, d = qnta.stochastic(data.sel(field='high'), data.sel(field='low'), data.sel(field='close'), 14)

    volatility = qnta.tr(data.sel(field='high'), data.sel(field='low'), data.sel(field='close'))
    volatility = volatility / data.sel(field='close')
    volatility = qnta.lwma(volatility, 14)

    volume = data.sel(field='vol')
    volume = qnta.sma(volume, 5) / qnta.sma(volume, 60)
    volume = volume.where(np.isfinite(volume), 0)

    # combine the selected four features:
    result = xr.concat(
        [trend, d, volatility, volume],
        pd.Index(
            ['trend', 'stochastic_d', 'volatility', 'volume'],
            name = 'field'
        )
    )
    
    return result.transpose('time', 'field', 'asset')
In [5]:
def get_target_classes(data):
    """Builds target classes which will be later predicted."""

    price_current = data.sel(field='close')
    price_future = qnta.shift(price_current, -1)

    class_positive = 1
    class_negative = 0

    target_is_price_up = xr.where(price_future > price_current, class_positive, class_negative)
    
    return target_is_price_up
In [6]:
def create_and_train_models(data):
    """Create and train the models working on an asset-by-asset basis."""
    
    asset_name_all = data.coords['asset'].values

    data = data.sel(time=slice('2013-05-01',None)) # cut the noisy data head before 2013-05-01

    features_all = get_features(data)
    target_all = get_target_classes(data)

    models = dict()

    for asset_name in asset_name_all:
        
        # drop missing values:
        target_cur = target_all.sel(asset=asset_name).dropna('time', 'any')
        features_cur = features_all.sel(asset=asset_name).dropna('time', 'any')

        # align features and targets:
        target_for_learn_df, feature_for_learn_df = xr.align(target_cur, features_cur, join='inner')

        if len(features_cur.time) < 10:
            # not enough points for training
            continue

        model = create_model()
        
        try:
            model.fit(feature_for_learn_df.values, target_for_learn_df)
            models[asset_name] = model
        except KeyboardInterrupt as e:
            raise e
        except:
            logging.exception('model training failed')

    return models
In [7]:
def predict(models, data):
    """Performs prediction and generates output weights.
       Generation is performed for several days in order to speed 
       up the evaluation.
    """
    
    asset_name_all = data.coords['asset'].values
    weights = xr.zeros_like(data.sel(field='close'))
    
    for asset_name in asset_name_all:
        if asset_name in models:
            model = models[asset_name]
            features_all = get_features(data)
            features_cur = features_all.sel(asset=asset_name).dropna('time','any')
            if len(features_cur.time) < 1:
                continue
            try:
                weights.loc[dict(asset=asset_name,time=features_cur.time.values)] = model.predict(features_cur.values)
            except KeyboardInterrupt as e:
                raise e
            except:
                logging.exception('model prediction failed')
                
    return weights

The following cell runs the backtester into Machine Learning retraining mode. We specify the maximal length of the training period and the interval for retraining. Note that it is possible tor retrain the model every day after submissions to the Quantiacs servers.

In [8]:
weights = qnbt.backtest_ml(
    train=create_and_train_models,
    predict=predict,
    train_period=10*365,   # the data length for training in calendar days
    retrain_interval=365,  # how often we have to retrain models (calendar days)
    retrain_interval_after_submit=1, # how often retrain models after submission during evaluation (calendar days)
    predict_each_day=False,  # Is it necessary to call prediction for every day during backtesting?
                             # Set it to true if you suspect that get_features is looking forward.
    competition_type='cryptofutures',  # competition type
    lookback_period=365,      # how many calendar days are needed by the predict function to generate the output
    start_date='2014-01-01',  # backtest start date
    build_plots=True          # do you need the chart?
)
Run the last iteration...
100% (219152 of 219152) |################| Elapsed Time: 0:00:00 Time:  0:00:00
100% (4172 of 4172) |####################| Elapsed Time: 0:00:00 Time:  0:00:00
Output cleaning...
fix uniq
ffill if the current price is None...
Check missed dates...
Ok.
Normalization...
Output cleaning is complete.
Write output: /root/fractions.nc.gz
State saved.
---
Run First Iteration...
100% (17072 of 17072) |##################| Elapsed Time: 0:00:00 Time:  0:00:00
---
Run all iterations...
Load data...
100% (251072 of 251072) |################| Elapsed Time: 0:00:00 Time:  0:00:00
100% (234572 of 234572) |################| Elapsed Time: 0:00:00 Time:  0:00:00
Backtest...
100% (238172 of 238172) |################| Elapsed Time: 0:00:00 Time:  0:00:00
Output cleaning...
fix uniq
ffill if the current price is None...
Check missed dates...
Ok.
Normalization...
Output cleaning is complete.
Write output: /root/fractions.nc.gz
State saved.
---
Analyze results...
Check...
Check missed dates...
Ok.
Check the sharpe ratio...
Period: 2014-01-01 - 2024-09-12
Sharpe Ratio = 0.7312395107834025
ERROR! The Sharpe Ratio is too low. 0.7312395107834025 < 1
Improve the strategy and make sure that the in-sample Sharpe Ratio more than 1.
Check correlation.
WARNING! Can't calculate correlation.
Correlation check failed.
---
Align...
Calc global stats...
---
Calc stats per asset...
Build plots...
---
Output:
asset BTC
time
2024-09-03 1.0
2024-09-04 1.0
2024-09-05 1.0
2024-09-06 1.0
2024-09-07 1.0
2024-09-08 1.0
2024-09-09 1.0
2024-09-10 1.0
2024-09-11 1.0
2024-09-12 1.0
Stats:
field equity relative_return volatility underwater max_drawdown sharpe_ratio mean_return bias instruments avg_turnover avg_holding_time
time
2024-09-03 60.975402 -0.016848 0.641466 -0.185911 -0.855027 0.733215 0.470333 1.0 1.0 0.069579 43.493506
2024-09-04 60.765543 -0.003442 0.641386 -0.188713 -0.855027 0.732339 0.469712 1.0 1.0 0.069565 43.493506
2024-09-05 58.782309 -0.032637 0.641389 -0.215192 -0.855027 0.724993 0.465003 1.0 1.0 0.069555 43.493506
2024-09-06 55.630047 -0.053626 0.641530 -0.257278 -0.855027 0.712847 0.457313 1.0 1.0 0.069543 43.493506
2024-09-07 56.566218 0.016829 0.641464 -0.244779 -0.855027 0.716255 0.459452 1.0 1.0 0.069540 43.493506
2024-09-08 57.152205 0.010359 0.641387 -0.236955 -0.855027 0.718317 0.460720 1.0 1.0 0.069524 43.493506
2024-09-09 59.883682 0.047793 0.641461 -0.200487 -0.855027 0.727989 0.466977 1.0 1.0 0.069515 43.493506
2024-09-10 60.432662 0.009167 0.641383 -0.193158 -0.855027 0.729808 0.468086 1.0 1.0 0.069509 43.493506
2024-09-11 60.057789 -0.006203 0.641305 -0.198162 -0.855027 0.728338 0.467087 1.0 1.0 0.069493 43.493506
2024-09-12 60.918002 0.014323 0.641235 -0.186678 -0.855027 0.731240 0.468896 1.0 1.0 0.069479 43.410256
---
100% (3901 of 3901) |####################| Elapsed Time: 0:01:01 Time:  0:01:01