%% Run Backtests
% The MATLAB® backtesting engine runs backtests of portfolio investment strategies over timeseries of asset price data. After creating a set of backtest strategies using backtestStrategy and the backtest engine using backtestEngine, the runBacktest function executes the backtest. This example illustrates how to use the runBacktest function to test investment strategies.
%
%% Load Data
% Load one year of stock price data. For readability, this example only uses a subset of the DJIA stocks.

% Read table of daily adjusted close prices for 2006 DJIA stocks
T = readtable('dowPortfolio.xlsx');

% Prune the table on only hold the dates and selected stocks
timeColumn = "Dates";
assetSymbols = ["BA", "CAT", "DIS", "GE", "IBM", "MCD", "MSFT"];
T = T(:,[timeColumn assetSymbols]);

% Convert to timetable
pricesTT = table2timetable(T,'RowTimes','Dates');

% View the final asset price timetable
head(pricesTT)

%% Create Strategy
% In this introductory example, test an equal weighted investment strategy. This strategy invests an equal portion of the available capital into each asset. This example does describe the details about how create backtest strategies. For more information on creating backtest strategies, see backtestStrategy.
% Set the RebalanceFrequency to rebalance the portfolio every 60 days. This example does not use a lookback window to rebalance.

% Create the strategy
numAssets = size(pricesTT,2);
equalWeightsVector = ones(1,numAssets) / numAssets;
equalWeightsRebalanceFcn = @(~,~) equalWeightsVector;

ewStrategy = backtestStrategy("EqualWeighted",equalWeightsRebalanceFcn,...
    'RebalanceFrequency',60,...
    'LookbackWindow',0,...
    'TransactionCosts',0.005,...
    'InitialWeights',equalWeightsVector)

%
%% Run Backtest
% Create a backtesting engine and run a backtest over a year of stock data. For more information on creating backtest engines, see backtestEngine.

% Create the backtest engine. The backtest engine properties that hold the
% results are initialized to empty.
backtester = backtestEngine(ewStrategy)
% Run the backtest. The empty properties are now populated with
% timetables of detailed backtest results.
backtester = runBacktest(backtester,pricesTT)

%% Backtest Summary
% Use the summary function to generate a summary table of backtest results.

% Examing results. The summary table shows several performance metrics.
summary(backtester)

% Copyright 2020 The MathWorks, Inc.