backtest strategies using deep learning -凯发k8网页登录
construct trading strategies using a deep learning model and then backtest the strategies using the financial toolbox™ backtesting framework. the example uses deep learning toolbox™ to train a predictive model from a set of time series and demonstrates the steps necessary to convert the model output into trading signals. it builds a variety of trading strategies that backtest the signal data over a 5-year period.
this example illustrates the following workflow:
the focus of this example is on the workflow from data, to a trained model, to trading strategies, and finally to a backtest of the strategies. the deep learning model, its output, the subsequent trading signals, and the strategies are fictional. the intent is only to show the steps for developing and deploying this type of model.
load data
load the historical price data. this data set contains daily spot prices for 12 different energy products ranging from 1986 to 2021 and consists of the following time series:
wti — west texas intermediate light crude oil
brent — brent light crude oil
naturalgas — henry hub natural gas
propane — mon belvieu propane
kerosene — us gulf coast kerosene-type jet fuel
heatingoil — new york harbor no. 2 heating oil
gulfregular — us gulf coast conventional gasoline
laregular — los angeles reformulated rbob regular gasoline
nyregular — new york harbor conventional gasoline
gulfdiesel — us gulf coast ultra-low sulfur no. 2 diesel
ladiesel — los angeles ultra-low sulfur carb diesel
nydiesel — new york harbor ultra-low sulfur no. 2 diesel
the source of this data is the us energy information administration (nov 2021).
pricedata = load('energyprices.mat','energyprices'); pricedata = pricedata.energyprices; tail(pricedata)
time wti brent naturalgas propane kerosene heatingoil gulfregular laregular nyregular gulfdiesel ladiesel nydiesel ___________ _____ _____ __________ _______ ________ __________ ___________ _________ _________ __________ ________ ________ 22-oct-2021 84.53 85.43 5.1 1.485 2.312 2.414 2.481 2.671 2.571 2.49 2.559 2.558 25-oct-2021 84.64 84.85 5.72 1.378 2.326 2.429 2.506 2.691 2.591 2.501 2.573 2.572 26-oct-2021 85.64 85.11 5.59 1.398 2.339 2.436 2.552 2.636 2.591 2.511 2.598 2.573 27-oct-2021 82.66 84.12 5.91 1.365 2.271 2.368 2.469 2.566 2.508 2.443 2.535 2.505 28-oct-2021 82.78 83.4 5.68 1.36 2.278 2.363 2.471 2.583 2.518 2.448 2.57 2.51 29-oct-2021 83.5 83.1 5.49 1.383 2.285 2.342 2.485 2.662 2.537 2.429 2.573 2.487 01-nov-2021 84.08 84.51 5.22 1.385 2.301 2.364 2.457 2.597 2.494 2.445 2.599 2.511 02-nov-2021 83.91 84.42 5.33 1.388 2.3 2.405 2.466 2.601 2.596 2.441 2.595 2.51
clean and trim data
the price datasets do not all start at the same time. some datasets start later than others and have fewer data points. the following plot shows the time span for each price series.
serieslifespanplot(pricedata)
to avoid large spans of missing data, remove the series with shorter histories.
pricedata = removevars(pricedata,["nydiesel","gulfdiesel","laregular"]);
the remaining table variables contain sporadic missing elements (nan
s) due to holidays or other reasons. missing data is handled in a variety of ways depending on the dataset. in some cases, it may be appropriate to interpolate or use the function. in this example, you can remove the remaining nan
prices.
pricedata = rmmissing(pricedata);
then, convert the price data to a return series using the (financial toolbox) function. the final dataset consists of nine price series with daily data from 1997 through 2021.
returndata = tick2ret(pricedata)
returndata=6167×9 timetable
time wti brent naturalgas propane kerosene heatingoil gulfregular nyregular ladiesel
___________ __________ ___________ __________ __________ __________ __________ ___________ __________ __________
08-jan-1997 0.011429 0.00080775 -0.0052356 0 0.012931 0.010974 0.0014347 -0.0028369 -0.0065789
09-jan-1997 -0.0094162 0.0020178 -0.05 -0.036969 -0.0085106 -0.0013569 -0.024355 -0.024182 0
10-jan-1997 -0.0057034 -0.024567 0.085873 0.0095969 -0.010014 -0.012228 -0.0088106 -0.0058309 -0.0092715
13-jan-1997 -0.036329 -0.033443 0.020408 -0.024715 -0.034682 -0.037139 -0.02963 -0.036657 -0.0066845
15-jan-1997 0.029762 -0.0042717 0.085 -0.048733 0.023952 0.021429 0.0030534 0.0060883 -0.013459
16-jan-1997 -0.019268 0 0.085253 -0.028689 -0.019006 -0.020979 0.0060883 0.0030257 0.020464
17-jan-1997 -0.0019646 -0.018876 -0.16985 -0.016878 -0.020864 -0.02 -0.0060514 -0.0075415 0
20-jan-1997 -0.011811 -0.00043725 -0.16624 -0.027897 -0.022831 -0.021866 0.0015221 -0.013678 -0.0040107
21-jan-1997 -0.011952 0.0052493 -0.082822 -0.004415 -0.014019 -0.020864 0.021277 0.012327 -0.0067114
22-jan-1997 -0.016129 -0.0021758 0.020067 -0.0044346 0.031596 0.019787 0.013393 0.016743 0
23-jan-1997 -0.022541 0 -0.029508 -0.0022272 -0.0061256 -0.01194 -0.035242 0.010479 0.040541
24-jan-1997 0 -0.0056694 -0.11486 -0.075893 0.010786 0.0060423 0.0060883 -0.0088889 0.0064935
27-jan-1997 0 -0.010526 0.1374 0.016908 0.012195 0.009009 0.0030257 -0.0029895 0.029677
28-jan-1997 0.0020964 0.0026596 0.02349 -0.0047506 0.0090361 -0.0089286 -0.010558 -0.011994 0.04386
29-jan-1997 0.025105 0.017241 -0.045902 -0.042959 0.059701 0.033033 0.042683 0.018209 0.014406
30-jan-1997 0.012245 0.018253 -0.017182 0 0.016901 0.023256 -0.0087719 0.026826 0.047337
⋮
prepare data for training lstm model
prepare and partition the dataset in order to train the lstm model. the model uses a 30-day rolling window of trailing feature data and predicts the next day price changes for four of the assets: brent crude oil, natural gas, propane, and kerosene.
% model is trained using a 30-day rolling window to predict 1 day in the % future. historysize = 30; futuresize = 1; % model predicts returns for oil, natural gas, propane, and kerosene. outputvarname = ["brent" "naturalgas", "propane" "kerosene"]; numoutputs = numel(outputvarname); % start_idx and end_idx are the index positions in the returndata % timetable corresponding to the first and last date for making a prediction. start_idx = historysize 1; end_idx = height(returndata) - futuresize 1; numsamples = end_idx - start_idx 1; % the date_vector variable stores the dates for making predictions. date_vector = returndata.time(start_idx-1:end_idx-1);
convert the returndata
timetable to a numsamples
-by-1
cell array. each cell contains a numfeatures
-by-seqlength
matrix. the response variable is a numsamples
-by-numresponses
matrix.
network_features = cell(numsamples,1); network_responses = zeros(numsamples,numoutputs); for j = 1:numsamples network_features{j} = (returndata(j:j historysize-1,:).variables)'; network_responses(j,:) = ... (returndata(j historysize:j historysize futuresize-1,outputvarname).variables)'; end
split the network_features
and the network_responses
into three parts: training, validation, and backtesting. select the backtesting set as a set of sequential data points. the remainder of the data is randomly split into a training and a validation set. use the validation set to prevent overfitting while training the model. the backtesting set is not used in the training process, but it is reserved for the final strategy backtest.
% specify rows to use in the backtest (31-dec-2015 to 2-nov-2021). backtest_start_idx = find(date_vector < datetime(2016,1,1),1,'last'); backtest_indices = backtest_start_idx:size(network_responses,1); % specify data reserved for the backtest. xbacktest = network_features(backtest_indices); tbacktest = network_responses(backtest_indices,:); % remove the backtest data. network_features = network_features(1:backtest_indices(1)-1); network_responses = network_responses(1:backtest_indices(1)-1,:); % partition the remaining data into training and validation sets. rng('default'); cv_partition = cvpartition(size(network_features,1),'holdout',0.2); % training set xtraining = network_features(~cv_partition.test,:); ttraining = network_responses(~cv_partition.test,:); % validation set xvalidation = network_features(cv_partition.test,:); tvalidation = network_responses(cv_partition.test,:);
define lstm network architecture
specify the network architecture as a series of layers. for more information on lstm networks, see long short-term memory neural networks. the deep network designer is a powerful tool for designing deep learning models.
numfeatures = width(returndata); numhiddenunits_lstm = 10; layers_lstm = [ ... sequenceinputlayer(numfeatures) lstmlayer(numhiddenunits_lstm) layernormalizationlayer lstmlayer(numhiddenunits_lstm) layernormalizationlayer lstmlayer(numhiddenunits_lstm,'outputmode','last') layernormalizationlayer fullyconnectedlayer(numoutputs) regressionlayer];
specify training options for lstm model
next, you specify training options using the function. many training options are available and their use varies depending on your use case. use the to explore different network architectures and sets of network hyperparamters.
max_epochs = 500; mini_batch_size = 128; learning_rate = 1e-4; options_lstm = trainingoptions('adam', ... 'plots','training-progress', ... 'verbose',0, ... 'maxepochs',max_epochs, ... 'minibatchsize',mini_batch_size, ... 'shuffle','every-epoch', ... 'validationdata',{xvalidation,tvalidation}, ... 'validationfrequency',50, ... 'validationpatience',10, ... 'initiallearnrate',learning_rate, ... 'gradientthreshold',1);
train lstm model
train the lstm network. use the function to train the network until the network meets a stopping criteria. this process can take several minutes depending on the computer running the example. for more information on increasing the network training performance, see .
to avoid waiting for the network training, load the pretrained network by setting the dotrain
flag to false
. to train the network using , set the dotrain
flag to true
.
dotrain = false; if dotrain % train the lstm network. net_lstm = trainnetwork(xtraining,ttraining,layers_lstm,options_lstm); else % load the pretrained network. load lstmbacktestnetwork end
visualize training results
visualize the results of the trained model by comparing the predicted values against the actual values from the validation set.
% compare the actual returns to model predicted returns. actual = tvalidation; predicted = predict(net_lstm,xvalidation,'minibatchsize',mini_batch_size);
% overlay histogram of actual vs. predicted returns for the validation set. output_idx = 1; figure; [~,edges] = histcounts(actual(:,output_idx),100); histogram(actual(:,output_idx),edges); hold on histogram(predicted(:,output_idx),edges) hold off xlabel('percentage change in closing price') legend('actual','predicted') title(sprintf('%s: distribution of returns, actual vs. predicted', outputvarname(output_idx)))
% display the predicted vs. actual daily returns for the validation set. figure plot(actual(:,output_idx)) hold on plot(predicted(:,output_idx)) yline(0) legend({'actual','predicted'}) title(sprintf('%s: daily returns, actual vs. predicted', outputvarname(output_idx)))
% examine the residuals.
residuals = actual(:,output_idx) - predicted(:,output_idx);
figure;
normplot(residuals);
the actual data has fatter tails than the trained model predictions. the model predictions are not accurate, but the goal of this example is to show the workflow from loading data, to model development, to backtesting. a more sophisticated model with a larger and more varied set of training data is likely to have more predictive power.
prepare backtest data
use the predictions from the lstm model to build the backtest strategies. you can post-process the model output in a number of ways to create trading signals. however, for this example, take the model regression output and convert it to a timetable.
use with the trained network to generate model predictions over the backtest period.
backtestpred_lstm = predict(net_lstm,xbacktest,'minibatchsize',mini_batch_size);
convert the predictions to a trading signal timetable.
backtestsignaltt = timetable(date_vector(backtest_indices),backtestpred_lstm);
construct the prices timetable corresponding to the backtest time span. the backtest trades in and out of the four energy commodities. the prices timetable has the closing price for the day on which the prediction is made.
backtestpricett = pricedata(date_vector(backtest_indices),outputvarname);
set the risk-free rate to be 1% annualized. the backtest engine also supports setting the risk-free rate to a timetable containing the historical daily rates.
risk_free_rate = 0.01;
create backtest strategies
use (financial toolbox) to create four trading strategies based on the signal indicators. the following trading strategies are intended as examples to show how to convert the trading signals into actionable asset allocation strategies that you can then backtest:
long only — invest all capital across the assets with positive predicted return, proportional to their signal strength (predicted return).
long short — invest capital across the assets, both long and short positions, proportional to their signal strength.
best bet — invest all capital into the single asset with the highest predicted return.
equal weight — rebalance each day to equal-weighted allocation.
% specify 10 basis points as the trading cost. tradingcosts = 0.001; % invest in long positions proportionally to their predicted return. longstrategy = backteststrategy('longonly',@longonlyrebalancefcn, ... 'transactioncosts',tradingcosts, ... 'lookbackwindow',1); % invest in both long and short positions proportionally to their predicted returns. longshortstrategy = backteststrategy('longshort',@longshortrebalancefcn, ... 'transactioncosts',tradingcosts, ... 'lookbackwindow',1); % invest 100% of capital into single asset with highest predicted returns. bestbetstrategy = backteststrategy('bestbet',@bestbetrebalancefcn, ... 'transactioncosts',tradingcosts, ... 'lookbackwindow',1); % for comparison, invest in an equal-weighted (buy low and sell high) strategy. equalweightfcn = @(current_weights,prices,signal) ones(size(current_weights)) / numel(current_weights); equalweightstrategy = backteststrategy('equalweight',equalweightfcn, ... 'transactioncosts',tradingcosts, ... 'lookbackwindow',0);
put the strategies
into an array and then use (financial toolbox) to create the backtesting engine.
strategies = [longstrategy longshortstrategy bestbetstrategy equalweightstrategy];
bt = backtestengine(strategies,'riskfreerate',risk_free_rate);
run backtest
use (financial toolbox) to backtest the strategies over the backtest range.
bt = runbacktest(bt,backtestpricett,backtestsignaltt)
bt = backtestengine with properties: strategies: [1×4 backteststrategy] riskfreerate: 0.0100 cashborrowrate: 0 ratesconvention: "annualized" basis: 0 initialportfoliovalue: 10000 dateadjustment: "previous" numassets: 4 returns: [1462×4 timetable] positions: [1×1 struct] turnover: [1462×4 timetable] buycost: [1462×4 timetable] sellcost: [1462×4 timetable]
examine backtest results
use the (financial toolbox) and (financial toolbox) functions to summarize and plot the backtest results. this model and its derivative trading strategies are not expected to be profitable in a realistic trading scenario. however, this example illustrates a workflow that should be useful for practitioners with more comprehensive data sets and more sophisticated models and strategies.
summary(bt)
ans=9×4 table
longonly longshort bestbet equalweight
_________ _________ ________ ___________
totalreturn 5.6962 8.3314 3.0248 4.8347
sharperatio 0.062549 0.071321 0.044571 0.056775
volatility 0.025296 0.025795 0.031625 0.026712
averageturnover 0.1828 0.22754 0.2459 0.0095931
maxturnover 0.96059 0.97368 1 0.5
averagereturn 0.0016216 0.001879 0.001449 0.001556
maxdrawdown 0.73831 0.62935 0.81738 0.70509
averagebuycost 3.6293 7.1838 3.8139 0.20262
averagesellcost 3.6225 7.2171 3.8071 0.19578
figure; equitycurve(bt)
local functions
function new_weights = longonlyrebalancefcn(current_weights,pricestt,signaltt) %#ok% long only strategy, in proportion to the signal. signal = signaltt.backtestpred_lstm(end,:); if any(0 < signal) signal(signal < 0) = 0; new_weights = signal / sum(signal); else new_weights = zeros(size(current_weights)); end end function new_weights = longshortrebalancefcn(current_weights,pricestt,signaltt) %#ok % long/short strategy, in proportion to the signal signal = signaltt.backtestpred_lstm(end,:); abssum = sum(abs(signal)); if 0 < abssum new_weights = signal / abssum; else new_weights = zeros(size(current_weights)); end end function new_weights = bestbetrebalancefcn(current_weights,pricestt,signaltt) %#ok % best bet strategy, invest in the asset with the most upside. signal = signaltt.backtestpred_lstm(end,:); new_weights = zeros(size(current_weights)); new_weights(signal == max(signal)) = 1; end function serieslifespanplot(pricedata) % plot the lifespan of each time series. % specify all time series end on same day. d2 = numel(pricedata.time); % plot the lifespan patch for each series. numseries = size(pricedata,2); for i = 1:numseries % find start date index. d1 = find(~isnan(pricedata{:,i}),1,'first'); % plot patch. x = [d1 d1 d2 d2]; y = i [-0.4 0.4 0.4 -0.4]; patch(x,y,[0 0.4470 0.7410]) hold on end hold off % set the plot properties. xlim([-100 d2]); ylim([0.2 numseries 0.8]); yticks(1:numseries); yticklabels(pricedata.properties.variablenames'); flipud(gca); years = 1990:5:2021; xtick_idx = zeros(size(years)); for yidx = 1:numel(years) xtick_idx(yidx) = find(years(yidx) == year(pricedata.time),1,'first'); end xticks(xtick_idx); xticklabels(string(years)); title('time series life span'); end
see also
deep network designer | | | (financial toolbox) | (financial toolbox) | (financial toolbox) | (financial toolbox) | (financial toolbox)
related topics
- backtest investment strategies using financial toolbox™ (financial toolbox)
- (financial toolbox)
- (financial toolbox)
- (financial toolbox)