How to ignore NaN values in price2ret
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hi,
Is there any efficient code to get from vector [99;NaN;100;102] the following result:
[NaN;NaN;0.01010101;0.02] using the formula price2ret
it means that for the second day there is no return as there is no price, but for the third day matlab ignores NaN (in the second day) and instead it takes the price form the first day (99).
thanks
0 comentarios
Respuestas (1)
Satyam
el 11 de Feb. de 2025 a las 9:45
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!
0 comentarios
Ver también
Categorías
Más información sobre Financial Toolbox en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!