Aggregating time series with gabs in data?
Show older comments
I have three columns consisting of dates, seconds and prices, all numeric:
Date, Second, Price
20120903, 34000, 230.68
20120903, 34004, 230.70
20120903, 34005, 230.65
…
20120905, 33378, 231.10
20120905, 33379, 231,50
The seconds run for every date from 32400 till 59399, but with gaps. There are gaps in the dates too. I want to simplify my data and create predefined 10 second intervals, and then store the first observed price value from within that interval, as the price value for the whole interval. If there is no price value for that interval in the original data, i want to just store a 0 for the price. i.e. predefined intervals:
32400-32409
32410-32419
…
59390-59399
and a new output that looks like:
Date, Second, Price
20120903, 34000-34010, 230.68
…
20120905, 33370 - 33379, 231.10
I have tried using: https://se.mathworks.com/matlabcentral/answers/259202-reshape-dataset-with-time-intervals But I cant make it work for predefined intervals. Do any of you know a way?
Answers (1)
Guillaume
on 7 Dec 2015
The way to solve this is to transform your date and second into a single value that preserve the ordering. You can then discretise these single values according to your interval and use the discretisation to group your prices.
With your date format, the simplest way to merge it with the seconds is simply to add it to the seconds divided by 1e5:
prices = [20120903, 34000, 230.68
20120903, 34004, 230.70
20120903, 34005, 230.65
20120905, 33378, 231.10
20120905, 33379, 231.50]
dateseconds = prices(:, 1) + prices(:, 2)/1e5;
bins = dateseconds(1):10/1e5:dateseconds(end)+10/1e5; %bins of 10 seconds
bindest = discretize(dateseconds, bins); %discretise dateseconds into bins
groupedprices = accumarray(bindest, prices(:, 3), [], @(v) v(1)); %take the first price of each group
The nice thing about accumarray is that it's trivial to have the mean, std, or whatever you want for each group:
meanprices = accumarray(bins, prices(:, 3), [], @mean);
To tidy up:
groupedprices = [round(bins(1:numel(groupedprices)), mod(bins(1:numel(groupedprices)), 1)*1e5, groupedprices]
2 Comments
Holt
on 7 Dec 2015
Guillaume
on 7 Dec 2015
You can create the quantisation bins any way you want. I made it start at the first observation, but you can hard code it, or round it to the nearest 34000 or ...
bins = 20120903.34 : 10/1e5 : 20120905.33380;
Frankly, the bin creation is the easiest part of the answer, so take the time to understand the code I've written.
Categories
Find more on Financial Data in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!