How to ignore NaN values in price2ret
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
Satyam
le 11 Fév 2025
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 commentaires
Voir également
Catégories
En savoir plus sur Multirate Signal Processing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!