Moving average for time series with unequal intersections

I have a dataset for the price of a ticker on the exchange: time - price. But the intervals between data points are not equal - from 1 to 2 minutes.

What is the best practice for calculating a moving average for such a case? How to do it in matlab?

I am inclined to think that the weights of the points should depend on the time interval that was the last from the previous point. Do we have a function in Matlab to calculate a moving average with custom point weights?

+4
source share
4 answers

Here is an example of a β€œnaive” approach that I mentioned in the comments above:

% some data (unequally spaced in time, but monotonically non-decreasing)
t = sort(rand(50,1));
x = cumsum(rand(size(t))-0.5);

% linear interpolatation on equally-spaced intervals
tt = linspace(min(t), max(t), numel(t));
xx = interp1(t, x, tt, 'linear');

% plot two data vectors
plot(t, x, 'b.-', tt, xx, 'r.:')
legend({'original', 'equally-spaced'})

interpolated_data_plot

+3
source

. .

, - , .

, . . . : x f(x). x=5, f(x) undefined.

- , . - " ", .

. , , , , ( , 2 ). . "" , "". , , , .

- 5 , . , , ( ) " ".

% reproduce your scenario
N = 20;
max_interval = 5;
time = randi(max_interval,N,1);
time(1) = 1; % first minute
price = randi(10,N,1);
figure(1)
plot(cumsum(time), price, 'ko-', 'LineWidth', 2);
hold on
% "keeping-previous-value" interpolation
interp1 = zeros(sum(time),1)-1;
interp1(cumsum(time)) = price;
while ismember(-1, interp1)
    interp1(interp1==-1) = interp1(find(interp1==-1)-1); 
end
plot(interp1, 'bx--')
% "midpoint" interpolation
interp2 = zeros(sum(time),1)-1;
interp2(cumsum(time)) = price;
for ii = 1:length(interp2)
    if interp2(ii) == -1
        t1 = interp2(ii-1);
        t2 = interp2( find(interp2(ii:end)>-1, 1, 'first') +ii-1);
        interp2(ii) = (t1+t2)/2;
    end
end
plot(interp2, 'rd--')
% "modified-midpoint" interpolation
interp3 = zeros(sum(time),1)-1;
interp3(cumsum(time)) = price;
for ii = 1:length(interp3)
    if interp3(ii) == -1
        t1 = interp3(ii-1);
        t2 = interp3( find(interp3(ii:end)>-1, 1, 'first') +ii-1);
        alpha = 1 / find(interp3(ii:end)>-1, 1, 'first');
        interp3(ii) = (1-alpha)*t1 + alpha*t2;
    end
end
plot(interp3, 'm^--')

hold off
legend('original data', 'interp 1', 'interp 2', 'interp 3')
fprintf(['"keeping-previous-value" (weighted sum) \n', ...
    '    result: %2.4f \n'], mean(interp1));
fprintf(['"midpoint" (linear interpolation) \n', ...
    '    result: %2.4f \n'], mean(interp2));
fprintf(['"modified-midpoint" (linear interpolation) \n', ...
    '    result: %2.4f \n'], mean(interp3));

. undefined NaN, -1 .

+2

, . , , , , O (1) , .

, "" . , , / .

, , . , . , . . , . - MATLAB.

+1

.

Since you have unequal data intervals, convert them to equal data intervals, keeping prices constant between unequal intervals.

Then you can use tsmovavg to calculate the moving average price range.

+1
source

All Articles