Hi,
To handle ‘NaN’ values in a price series while calculating returns, you can preprocess the data to fill ‘NaN’ values with the last available price using the ‘fillmissing’ function, which effectively ignores the ‘NaN’ in the calculation of returns. More details on ‘fillmissing’ can be found: https://www.mathworks.com/help/releases/R2024a/matlab/ref/fillmissing.html
After calculating the returns, we restore ‘NaN’ at positions where the original price vector had ‘NaN’ values, except for the first position since it doesn't affect return calculation.
Here is the code to explain it better:
prices = [99; NaN; 100; 102];
% Fill NaN values with the last available price
filledPrices = fillmissing(prices, 'previous');
returns = price2ret(filledPrices,'Method','periodic');
% Adjust returns to reflect the presence of NaN in the original data
% Set returns to NaN where the original data had NaN
returns(isnan(prices(2:end))) = NaN;
disp(returns);
I hope it helps!