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% (31314 of 31314) |##################| Elapsed Time: 0:00:00 Time:  0:00:00
100% (186952 of 186952) |################| 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
2017-06-19 NaN NaN
2017-06-20 NaN NaN
2017-06-21 NaN NaN
2017-06-22 NaN NaN
2017-06-23 NaN NaN
... ... ...
2022-06-10 -0.464477 -0.705388
2022-06-13 -0.571594 -0.848583
2022-06-14 -0.545459 -0.868234
2022-06-15 -0.479005 -0.706186
2022-06-16 -0.587847 -0.795070

1259 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
2017-06-19 0 0
2017-06-20 1 1
2017-06-21 0 0
2017-06-22 1 1
2017-06-23 0 0
... ... ...
2022-06-10 0 0
2022-06-13 1 0
2022-06-14 1 1
2022-06-15 0 0
2022-06-16 0 0

1259 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.00001
Feature: 1, Score: 0.00002
Feature: 2, Score: -0.00000
Feature: 3, Score: 0.00015
Feature: 4, Score: 0.00013
Feature: 5, Score: -0.00006
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: 1259, asset: 2)>
array([[0.        , 0.        ],
       [0.        , 0.        ],
       [0.        , 0.        ],
       ...,
       [0.51947717, 0.53154922],
       [0.52097527, 0.53170227],
       [0.52051077, 0.53155162]])
Coordinates:
  * asset    (asset) <U8 'NAS:AAPL' 'NAS:AMZN'
  * time     (time) datetime64[ns] 2017-06-19 2017-06-20 ... 2022-06-16
    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.7599407010807633

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
2022-06-10 2.861688 -0.046640 0.289733 -0.300710 -0.346304 0.811300 0.235061 1.0 2.0 0.016556 484.329587
2022-06-13 2.731976 -0.045327 0.290360 -0.332407 -0.346304 0.769437 0.223414 1.0 2.0 0.016561 485.414973
2022-06-14 2.721904 -0.003686 0.290252 -0.334868 -0.346304 0.765928 0.222312 1.0 2.0 0.016552 486.294070
2022-06-15 2.820963 0.036393 0.290569 -0.310661 -0.346304 0.794646 0.230900 1.0 2.0 0.016564 486.589931
2022-06-16 2.713097 -0.038237 0.290983 -0.337020 -0.346304 0.759941 0.221130 1.0 2.0 0.016578 737.179374
time 2022-06-16
field
sharpe_ratio 0.759941
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.05604942076291564
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.05335589232939786
In [16]:
"""The explained variance score explains the dispersion of errors of a given dataset"""
mean_absolute_error(my_targetclass, weights)
Out[16]:
0.49981113967909496

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% (17055 of 17055) |##################| Elapsed Time: 0:00:00 Time:  0:00:00
100% (4558236 of 4558236) |##############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 1/1 1s
Data loaded 1s
100% (380056 of 380056) |################| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 1/1 1s
Data loaded 1s
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% (12814 of 12814) |##################| Elapsed Time: 0:00:00 Time:  0:00:00
100% (3355548 of 3355548) |##############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 1/1 1s
Data loaded 1s
---
Run all iterations...
Load data...
100% (34173 of 34173) |##################| Elapsed Time: 0:00:00 Time:  0:00:00
100% (14862360 of 14862360) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 1/7 1s
100% (14862360 of 14862360) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 2/7 2s
100% (14862332 of 14862332) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 3/7 3s
100% (14862252 of 14862252) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 4/7 4s
100% (14885324 of 14885324) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 5/7 5s
100% (15107472 of 15107472) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 6/7 7s
100% (2247380 of 2247380) |##############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 7/7 7s
Data loaded 7s
100% (32016 of 32016) |##################| Elapsed Time: 0:00:00 Time:  0:00:00
100% (14891460 of 14891460) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 1/5 1s
100% (14891460 of 14891460) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 2/5 2s
100% (14891424 of 14891424) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 3/5 4s
100% (14891332 of 14891332) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 4/5 5s
100% (13889116 of 13889116) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 5/5 6s
Data loaded 6s
Backtest...
100% (32290 of 32290) |##################| Elapsed Time: 0:00:00 Time:  0:00:00
100% (14707648 of 14707648) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 1/6 1s
100% (14707644 of 14707644) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 2/6 2s
100% (14707612 of 14707612) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 3/6 3s
100% (14707520 of 14707520) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 4/6 4s
100% (14989472 of 14989472) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 5/6 6s
100% (976336 of 976336) |################| 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 - 2022-06-16
Sharpe Ratio = 0.38985762975619004
ERROR! The Sharpe Ratio is too low. 0.38985762975619004 < 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
2022-06-03 0.0 0.007219 0.0 0.007921 0.007268 0.008325 0.006998 0.007293 0.0 0.006981
2022-06-06 0.0 0.007231 0.0 0.007991 0.007264 0.008428 0.006996 0.007290 0.0 0.007042
2022-06-07 0.0 0.007209 0.0 0.007648 0.007186 0.008123 0.006980 0.007254 0.0 0.007167
2022-06-08 0.0 0.007160 0.0 0.007827 0.007213 0.008264 0.006964 0.007257 0.0 0.007139
2022-06-09 0.0 0.007085 0.0 0.007774 0.007198 0.008358 0.006902 0.007179 0.0 0.007113
2022-06-10 0.0 0.007126 0.0 0.008318 0.007231 0.008030 0.006880 0.007112 0.0 0.007139
2022-06-13 0.0 0.007159 0.0 0.008169 0.007326 0.007847 0.006880 0.007094 0.0 0.007208
2022-06-14 0.0 0.007195 0.0 0.007523 0.007317 0.007532 0.006891 0.007096 0.0 0.007190
2022-06-15 0.0 0.007201 0.0 0.007318 0.007267 0.007354 0.006913 0.007128 0.0 0.007214
2022-06-16 0.0 0.007154 0.0 0.007675 0.007325 0.007725 0.006888 0.007082 0.0 0.007173
Stats:
field equity relative_return volatility underwater max_drawdown sharpe_ratio mean_return bias instruments avg_turnover avg_holding_time
time
2022-06-03 3.843500 -0.011754 0.188111 -0.102781 -0.589048 0.427756 0.080466 1.0 204.0 0.034013 47.252549
2022-06-06 3.845484 0.000516 0.188090 -0.102318 -0.589048 0.427875 0.080479 1.0 204.0 0.034008 47.266289
2022-06-07 3.864748 0.005010 0.188073 -0.097821 -0.589048 0.429465 0.080771 1.0 204.0 0.034004 47.269495
2022-06-08 3.843593 -0.005474 0.188057 -0.102760 -0.589048 0.427590 0.080411 1.0 204.0 0.034001 47.281712
2022-06-09 3.790053 -0.013930 0.188067 -0.115258 -0.589048 0.422841 0.079522 1.0 205.0 0.033996 47.293625
2022-06-10 3.709747 -0.021189 0.188117 -0.134004 -0.589048 0.415579 0.078177 1.0 205.0 0.033994 47.326321
2022-06-13 3.620382 -0.024089 0.188187 -0.154866 -0.589048 0.407314 0.076651 1.0 205.0 0.033992 47.347185
2022-06-14 3.617791 -0.000716 0.188166 -0.155470 -0.589048 0.407030 0.076589 1.0 205.0 0.033988 47.365864
2022-06-15 3.656415 0.010676 0.188161 -0.146454 -0.589048 0.410433 0.077228 1.0 205.0 0.033984 47.372242
2022-06-16 3.572824 -0.022861 0.188223 -0.165967 -0.589048 0.402617 0.075782 1.0 205.0 0.033979 49.854571