How to deal with asset data having zeros in part when backtesting with 'runBacktest'?

1 view (last 30 days)
When backtesting with the functions 'backtestStrategy', 'backtestEngine', and 'runBacktest', I have an issue with an asset data including zeros.
The following code is an example, which equally weights 4 stocks with rebalancing the portfolio every 20 days. The following code works as expeted.
%% create a pseudo stock price table.
d = datetime('2020-01-01'):caldays(1):datetime('2020-12-31'); % create a date array
price = rand(numel(d), 4); % create a pseudo stock prices
% price(:,4) = 0;
priceTT = array2timetable(price, 'RowTimes', d', ...
'VariableNames', {'Stock_A', 'Stock_B', 'Stock_C', 'Stock_d'});
%% create a backtesting strategy which equally weights all stocks and rebalances every 20 days
nAsset = size(priceTT, 2);
initial_weights = ones(1,nAsset) / nAsset;
equalWeightFn = @(~, ~) initial_weights;
strategy = backtestStrategy('EqualWeighting', equalWeightFn, ...
'InitialWeights', initial_weights, ...
'TransactionCosts', 0 , ...
'RebalanceFrequency', 20);
%% create a backtest engine and run backtest.
backtester = backtestEngine(strategy);
bt = runBacktest(backtester, priceTT);
%% summry the backtest result.
summary(bt)
However, when the prices of 'Stock_d' is replaced with zeros (please uncomment the third line in the example, "prices(:,4) = 0"), all the backtesting results becomes as below.
EqualWeighting
______________
TotalReturn NaN
SharpeRatio NaN
Volatility NaN
AverageTurnover NaN
MaxTurnover 0
AverageReturn NaN
MaxDrawdown NaN
AverageBuyCost 0
AverageSellCost 0
Please advise me whey an asset data including a stocks with zeros does not work.
Thank you for any comment in advance.
  3 Comments
Brendan
Brendan on 16 Aug 2021
Peter is correct. In the latest version of the financial toolbox you will get a more helpful error message if you attempt to invest in an asset that has an invalid return (for example and Inf for NaN return).
backtest strategy rebalance functions should take care to avoid investing in assets that encounter invalid return data.
Doheon Lee
Doheon Lee on 27 Aug 2021
Thank you, Peter and Brenda,
My MATLAB is 2021a, and I still have thie problem. Instead of zeoring for NaN values in a table containing historica stock prices, I replaced NaN with 1e-10, which is close to zero and it works fine. That is, replacing the third line with the following,
price(:,4) = ie-10;
Thank you for the comments. :)

Sign in to comment.

Answers (0)

Categories

Find more on Portfolio Optimization and Asset Allocation in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!