How to ignore NaN values in price2ret

2 ビュー (過去 30 日間)
BdS
BdS 2020 年 4 月 15 日
回答済み: Satyam 2025 年 2 月 11 日
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

回答 (1 件)

Satyam
Satyam 2025 年 2 月 11 日
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);
NaN 0.0101 0.0200
I hope it helps!

カテゴリ

Help Center および File ExchangeMultirate Signal Processing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by