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 CenterFile Exchange에서 Multirate Signal Processing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by