strategy

Q18 Machine Learning on a Rolling Basis

This example shows how to make a submission to the stock contest using machine learning and retraining.

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


In this example we predict whether the price will rise or fall by using supervised learning (Bayesian Ridge Regression). This template represents a starting point for developing a system which can take part to the Q18 NASDAQ-100 Stock Long-Short contest.

It consists of two parts.

  • In the first part we just perform a global training of the time series using all time series data. We disregard the sequential aspect of the data and use also future data to train past data.

  • In the second part we use the built-in backtester and perform training and prediction on a rolling basis in order to avoid forward looking. Please note that we are using a specialized version of the Quantiacs backtester which dramatically speeds up the the backtesting process by retraining your model on a regular basis.

Features for learning: we will use several technical indicators trying to capture different features. You can have a look at Technical Indicators.

Please note that:

  • Your trading algorithm can open short and long positions.

  • At each point in time your algorithm can trade all or a subset of the stocks which at that point of time are or were part of the NASDAQ-100 stock index. Note that the composition of this set changes in time, and Quantiacs provides you with an appropriate filter function for selecting them.

  • The Sharpe ratio of your system since January 1st, 2006, has to be larger than 1.

  • Your system cannot be a copy of the current examples. We run a correlation filter on the submissions and detect duplicates.

  • For simplicity we will use a single asset. It pays off to use more assets, ideally uncorrelated, and diversify your positions for a more solid Sharpe ratio.

More details on the rules can be found here.

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.

Need to use the optimizer function to automate tedious tasks?

  • optimization: read more on our article.
In [1]:
%%javascript
IPython.OutputArea.prototype._should_scroll = function(lines) { return false; }
// disable widget scrolling
In [2]:
import logging

import xarray as xr  # xarray for data manipulation

import qnt.data as qndata     # functions for loading data
import qnt.backtester as qnbt # built-in backtester
import qnt.ta as qnta         # technical analysis library
import qnt.stats as qnstats   # statistical functions

import pandas as pd
import numpy as np

import matplotlib.pyplot as plt

np.seterr(divide = "ignore")

from qnt.ta.macd import macd
from qnt.ta.rsi  import rsi
from qnt.ta.stochastic import stochastic_k, stochastic, slow_stochastic

from sklearn import linear_model
from sklearn.metrics import r2_score
from sklearn.metrics import explained_variance_score
from sklearn.metrics import mean_absolute_error
In [3]:
# loading nasdaq-100 stock data

stock_data = qndata.stocks.load_ndx_data(tail = 365 * 5, assets = ["NAS:AAPL", "NAS:AMZN"])
100% (364802 of 364802) |################| Elapsed Time: 0:00:00 Time:  0:00:00
100% (38058 of 38058) |##################| Elapsed Time: 0:00:00 Time:  0:00:00
100% (186508 of 186508) |################| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 1/1 0s
Data loaded 0s
In [4]:
def get_features(data):
    """Builds the features used for learning:
       * a trend indicator;
       * the moving average convergence divergence;
       * a volatility measure; 
       * the stochastic oscillator;
       * the relative strength index;
       * the logarithm of the closing price.
       These features can be modified and new ones can be added easily.
    """
   
    # trend:
    trend = qnta.roc(qnta.lwma(data.sel(field="close"), 60), 1)
     
    # moving average convergence  divergence (MACD):
    macd = qnta.macd(data.sel(field="close"))
    macd2_line, macd2_signal, macd2_hist = qnta.macd(data, 12, 26, 9)

    # volatility:
    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)

    # the stochastic oscillator:
    k, d = qnta.stochastic(data.sel(field="high"), data.sel(field="low"), data.sel(field="close"), 14)
    
    # the relative strength index: 
    rsi = qnta.rsi(data.sel(field="close"))
    
    # the logarithm of the closing price:
    price = data.sel(field="close").ffill("time").bfill("time").fillna(0) # fill NaN
    price = np.log(price)
    
    # combine the six features:
    result = xr.concat(
        [trend, macd2_signal.sel(field="close"), volatility,  d, rsi, price],
        pd.Index(
            ["trend",  "macd", "volatility", "stochastic_d", "rsi", "price"],
            name = "field"
        )
    )

    return result.transpose("time", "field", "asset")
In [5]:
# displaying the features:
my_features = get_features(stock_data)
display(my_features.sel(field="trend").to_pandas())
asset NAS:AAPL NAS:AMZN
time
2018-09-14 NaN NaN
2018-09-17 NaN NaN
2018-09-18 NaN NaN
2018-09-19 NaN NaN
2018-09-20 NaN NaN
... ... ...
2023-09-06 -0.061803 0.083166
2023-09-07 -0.157197 0.139171
2023-09-08 -0.144601 0.143670
2023-09-11 -0.122323 0.257610
2023-09-12 -0.175553 0.204661

1256 rows × 2 columns

In [6]:
def get_target_classes(data):
    """ Target classes for predicting if price goes up or down."""
    
    price_current = data.sel(field="close")
    price_future  = qnta.shift(price_current, -1)

    class_positive = 1 # prices goes up
    class_negative = 0 # price goes down

    target_price_up = xr.where(price_future > price_current, class_positive, class_negative)

    return target_price_up
In [7]:
# displaying the target classes:
my_targetclass = get_target_classes(stock_data)
display(my_targetclass.to_pandas())
asset NAS:AAPL NAS:AMZN
time
2018-09-14 0 0
2018-09-17 1 1
2018-09-18 1 0
2018-09-19 1 1
2018-09-20 0 0
... ... ...
2023-09-06 0 1
2023-09-07 1 1
2023-09-08 1 1
2023-09-11 0 0
2023-09-12 0 0

1256 rows × 2 columns

In [8]:
def get_model():
    """This is a constructor for the ML model (Bayesian Ridge) which can be easily 
       modified for using different models.
    """
    
    model = linear_model.BayesianRidge()
    return model
In [9]:
# Create and train the models working on an asset-by-asset basis.

asset_name_all = stock_data.coords["asset"].values

models = dict()

for asset_name in asset_name_all:

        # drop missing values:
        target_cur   = my_targetclass.sel(asset=asset_name).dropna("time", "any")
        features_cur = my_features.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 = get_model()

        try:
            model.fit(feature_for_learn_df.values, target_for_learn_df)
            models[asset_name] = model
                
        except:
            logging.exception("model training failed")
            
print(models)
{'NAS:AAPL': BayesianRidge(), 'NAS:AMZN': BayesianRidge()}
In [10]:
# Showing which features are more important in predicting:

importance = models["NAS:AAPL"].coef_
importance

for i,v in enumerate(importance):
    print('Feature: %0d, Score: %.5f' % (i,v))
    
plt.bar([x for x in range(len(importance))], importance)
plt.show()
Feature: 0, Score: -0.00002
Feature: 1, Score: -0.00034
Feature: 2, Score: -0.00000
Feature: 3, Score: 0.00030
Feature: 4, Score: -0.00049
Feature: 5, Score: -0.00013
In [11]:
# Performs prediction and generates output weights:

asset_name_all = stock_data.coords["asset"].values
weights = xr.zeros_like(stock_data.sel(field="close"))
    
for asset_name in asset_name_all:
    if asset_name in models:
        model = models[asset_name]
        features_all = my_features
        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")
            
print(weights)
<xarray.DataArray 'stocks_nasdaq100' (time: 1256, asset: 2)>
array([[0.        , 0.        ],
       [0.        , 0.        ],
       [0.        , 0.        ],
       ...,
       [0.53410853, 0.51737645],
       [0.53052145, 0.51217108],
       [0.53119455, 0.51347828]])
Coordinates:
  * asset    (asset) <U8 'NAS:AAPL' 'NAS:AMZN'
  * time     (time) datetime64[ns] 2018-09-14 2018-09-17 ... 2023-09-12
    field    <U5 'close'
In [12]:
def get_sharpe(stock_data, weights):
    """Calculates the Sharpe ratio"""
    rr = qnstats.calc_relative_return(stock_data, weights)
    sharpe = qnstats.calc_sharpe_ratio_annualized(rr).values[-1]
    return sharpe

sharpe = get_sharpe(stock_data, weights)
sharpe
Out[12]:
0.7504038834910517

The sharpe ratio using the method above follows from forward looking. Predictions for (let us say) 2017 know about the relation between features and targets in 2020. Let us visualize the results:

In [13]:
import qnt.graph as qngraph

statistics = qnstats.calc_stat(stock_data, weights)

display(statistics.to_pandas().tail())

performance = statistics.to_pandas()["equity"]
qngraph.make_plot_filled(performance.index, performance, name="PnL (Equity)", type="log")

display(statistics[-1:].sel(field = ["sharpe_ratio"]).transpose().to_pandas())

# check for correlations with existing strategies:
qnstats.print_correlation(weights,stock_data)
field equity relative_return volatility underwater max_drawdown sharpe_ratio mean_return bias instruments avg_turnover avg_holding_time
time
2023-09-06 2.765285 -0.024945 0.301284 -0.085739 -0.413378 0.750770 0.226195 1.0 2.0 0.018132 378.223084
2023-09-07 2.748208 -0.006175 0.301181 -0.091385 -0.413378 0.745317 0.224475 1.0 2.0 0.018149 378.258642
2023-09-08 2.756454 0.003000 0.301062 -0.088659 -0.413378 0.747393 0.225012 1.0 2.0 0.018148 378.306601
2023-09-11 2.813529 0.020706 0.301072 -0.069788 -0.413378 0.763422 0.229845 1.0 2.0 0.018140 378.717519
2023-09-12 2.770945 -0.015135 0.301038 -0.083867 -0.413378 0.750404 0.225900 1.0 2.0 0.018147 459.293046
time 2023-09-12
field
sharpe_ratio 0.750404
Ok. This strategy does not correlate with other strategies.
In [14]:
"""R2 (coefficient of determination) regression score function."""
r2_score(my_targetclass, weights, multioutput="variance_weighted")
Out[14]:
-0.03896132711651169
In [15]:
"""The explained variance score explains the dispersion of errors of a given dataset"""
explained_variance_score(my_targetclass, weights, multioutput="uniform_average")
Out[15]:
-0.03704003600300754
In [16]:
"""The explained variance score explains the dispersion of errors of a given dataset"""
mean_absolute_error(my_targetclass, weights)
Out[16]:
0.4963463248676872

Let us now use the Quantiacs backtester for avoiding forward looking.

The backtester performs some transformations: it trains the model on one slice of data (using only data from the past) and predicts the weights for the following slice on a rolling basis:

In [17]:
def train_model(data):
    """Create and train the model working on an asset-by-asset basis."""
    
    asset_name_all = data.coords["asset"].values
    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")
        
        target_for_learn_df, feature_for_learn_df = xr.align(target_cur, features_cur, join="inner")
        
        if len(features_cur.time) < 10:
                continue
                
        model = get_model()
        
        try:
            model.fit(feature_for_learn_df.values, target_for_learn_df)
            models[asset_name] = model
                
        except:
            logging.exception("model training failed")

    return models
In [18]:
def predict_weights(models, data):
    """The model predicts if the price is going up or down.
       The prediction 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
In [19]:
# Calculate weights using the backtester:
weights = qnbt.backtest_ml(
    train                         = train_model,
    predict                       = predict_weights,
    train_period                  =  2 *365,  # the data length for training in calendar days
    retrain_interval              = 10 *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              = "stocks_nasdaq100",  # competition type
    lookback_period               = 365,                 # how many calendar days are needed by the predict function to generate the output
    start_date                    = "2005-01-01",        # backtest start date
    analyze                       = True,
    build_plots                   = True  # do you need the chart?
)
Run the last iteration...
100% (38058 of 38058) |##################| Elapsed Time: 0:00:00 Time:  0:00:00
100% (8842476 of 8842476) |##############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 1/1 2s
Data loaded 2s
100% (724212 of 724212) |################| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 1/1 2s
Data loaded 2s
Output cleaning...
fix uniq
ffill if the current price is None...
Check liquidity...
WARNING! Strategy trades non-liquid assets.
Fix liquidity...
Ok.
Check missed dates...
Ok.
Normalization...
Output cleaning is complete.
Write output: /root/fractions.nc.gz
State saved.
---
Run First Iteration...
100% (38058 of 38058) |##################| Elapsed Time: 0:00:00 Time:  0:00:00
100% (8895192 of 8895192) |##############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 1/1 3s
Data loaded 3s
---
Run all iterations...
Load data...
100% (38058 of 38058) |##################| Elapsed Time: 0:00:00 Time:  0:00:00
100% (14576356 of 14576356) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 1/7 1s
100% (14579020 of 14579020) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 2/7 2s
100% (14576328 of 14576328) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 3/7 3s
100% (14576328 of 14576328) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 4/7 4s
100% (14597600 of 14597600) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 5/7 5s
100% (14576256 of 14576256) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 6/7 6s
100% (8676108 of 8676108) |##############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 7/7 6s
Data loaded 7s
100% (14586648 of 14586648) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 1/6 1s
100% (14589744 of 14589744) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 2/6 2s
100% (14586616 of 14586616) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 3/6 3s
100% (14586532 of 14586532) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 4/6 4s
100% (14586532 of 14586532) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 5/6 5s
100% (9843808 of 9843808) |##############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 6/6 6s
Data loaded 6s
Backtest...
100% (38058 of 38058) |##################| Elapsed Time: 0:00:00 Time:  0:00:00
100% (14710648 of 14710648) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 1/6 1s
100% (14713744 of 14713744) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 2/6 2s
100% (14710616 of 14710616) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 3/6 3s
100% (14710532 of 14710532) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 4/6 4s
100% (14710532 of 14710532) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 5/6 5s
100% (9927488 of 9927488) |##############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 6/6 6s
Data loaded 6s
Output cleaning...
fix uniq
ffill if the current price is None...
Check liquidity...
WARNING! Strategy trades non-liquid assets.
Fix liquidity...
Ok.
Check missed dates...
Ok.
Normalization...
Output cleaning is complete.
Write output: /root/fractions.nc.gz
State saved.
---
Analyze results...
Check...
Check liquidity...
Ok.
Check missed dates...
Ok.
Check the sharpe ratio...
Period: 2006-01-01 - 2023-09-12
Sharpe Ratio = 0.48084540822269506
ERROR! The Sharpe Ratio is too low. 0.48084540822269506 < 1
Improve the strategy and make sure that the in-sample Sharpe Ratio more than 1.
Check correlation.

Ok. This strategy does not correlate with other strategies.
---
Align...
Calc global stats...
---
Calc stats per asset...
Build plots...
---
Output:
asset NAS:AAL NAS:AAPL NAS:ABNB NAS:ADBE NAS:ADI NAS:ADP NAS:ADSK NAS:AEP NAS:AKAM NAS:ALGN
time
2023-08-29 0.0 0.006881 0.0 0.006812 0.007067 0.006908 0.006647 0.007035 0.0 0.006525
2023-08-30 0.0 0.006862 0.0 0.007029 0.007131 0.006880 0.006665 0.007067 0.0 0.006431
2023-08-31 0.0 0.006859 0.0 0.006736 0.007134 0.006932 0.006669 0.007092 0.0 0.006358
2023-09-01 0.0 0.006861 0.0 0.006543 0.007126 0.006861 0.006703 0.007118 0.0 0.006346
2023-09-05 0.0 0.006835 0.0 0.006391 0.007133 0.007290 0.006688 0.007111 0.0 0.006366
2023-09-06 0.0 0.006895 0.0 0.006527 0.007100 0.007299 0.006664 0.007090 0.0 0.006367
2023-09-07 0.0 0.006967 0.0 0.006576 0.007203 0.006950 0.006655 0.007042 0.0 0.006704
2023-09-08 0.0 0.007034 0.0 0.006482 0.007217 0.006751 0.006664 0.007020 0.0 0.006945
2023-09-11 0.0 0.007080 0.0 0.006334 0.007224 0.006866 0.006695 0.007040 0.0 0.007190
2023-09-12 0.0 0.007076 0.0 0.007621 0.007270 0.006822 0.006741 0.007009 0.0 0.007182
Stats:
field equity relative_return volatility underwater max_drawdown sharpe_ratio mean_return bias instruments avg_turnover avg_holding_time
time
2023-08-29 5.058240 0.009050 0.184932 -0.014536 -0.560008 0.491335 0.090864 1.0 211.0 0.022215 130.896778
2023-08-30 5.071147 0.002552 0.184913 -0.012021 -0.560008 0.492083 0.090993 1.0 211.0 0.022214 130.894731
2023-08-31 5.067801 -0.000660 0.184894 -0.012673 -0.560008 0.491816 0.090934 1.0 211.0 0.022212 130.892742
2023-09-01 5.075119 0.001444 0.184874 -0.011247 -0.560008 0.492216 0.090998 1.0 211.0 0.022210 130.891443
2023-09-05 5.058782 -0.003219 0.184856 -0.014430 -0.560008 0.491134 0.090789 1.0 211.0 0.022208 130.888397
2023-09-06 5.054263 -0.000893 0.184837 -0.015310 -0.560008 0.490793 0.090717 1.0 211.0 0.022206 130.903078
2023-09-07 5.034845 -0.003842 0.184820 -0.019093 -0.560008 0.489513 0.090472 1.0 211.0 0.022204 130.909285
2023-09-08 5.033839 -0.000200 0.184800 -0.019290 -0.560008 0.489393 0.090440 1.0 211.0 0.022202 130.921053
2023-09-11 5.048999 0.003012 0.184782 -0.016336 -0.560008 0.490284 0.090596 1.0 211.0 0.022199 130.928067
2023-09-12 5.028738 -0.004013 0.184765 -0.020283 -0.560008 0.488949 0.090341 1.0 211.0 0.022197 135.526339