I downloaded some EURUSD tick data (source) and already prepared it, so that I now have a dataframe with the bid and ask prize as well as the datetime. The datetime has been created with
options(digits.secs=3)
data$datetime <- as.POSIXct(strptime(as.character(data$datetime), format="%Y-%m-%d %H:%M:%OS"))
As you may see from the data, each minute can consist of a different number of prize points (ticks).
Now I'd like to calculate a moving average as if the data would have been compressed into a 1-minute chart, i.e. for each tick prize I'd like to calculate the average over the last x minutes, whereas only the current prize as well as the (x-1) last prizes of the (x-1) last minutes should be used. Maybe it is easier to explain with an example. Let's consider this data:
bid datetime
[1] 1.21332 2016-03-01 03:21:32.138
[2] 1.21333 2016-03-01 03:21:58.213
[3] 1.21328 2016-03-01 03:22:01.283
[4] 1.21325 2016-03-01 03:22:47.018
[5] 1.21330 2016-03-01 03:23:22.221
[6] 1.21331 2016-03-01 03:24:01.112
For the last data point [6] and a period (x) of 4 I now like to calculate the average of the last elapsed 3 minutes (using the last bid prize for each of these minutes) as well as the current value, i.e.
mean = ([2] + [4] + [5] + [6]) / 4
My approach would be using stacked loops (one to go over each data point and one to determine the last prize changes during the last elapsed (x-1) minutes). However, I'd bet that there is as faster and more efficient way to do this with R.
Thanks a lot in advance for your help!