Skip to content

Instantly share code, notes, and snippets.

@femtotrader
Last active December 5, 2017 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save femtotrader/89af55ef91f26f952835fd737a14847b to your computer and use it in GitHub Desktop.
Save femtotrader/89af55ef91f26f952835fd737a14847b to your computer and use it in GitHub Desktop.
using Temporal
import Base: mean
#using TimeFrames
#import TimeFrames: apply
struct TimeSeriesResampler
ts
tf
end
function names(ts::TS, dim)
if dim == 1
ts.index
elseif dim == 2
ts.fields
else
throw(Exception("Dim must be 1 or 2"))
end
end
function resample(ts, tf)
TimeSeriesResampler(ts, tf)
end
function mean(resampler::TimeSeriesResampler)
ts = resampler.ts
tf = resampler.tf
z = Dates.Millisecond(0) # doesn't work simply with z=0
idx1 = names(ts, 1)
idx2 = apply.(tf, idx1)
at = [true;diff(idx2).!=z]
ts2 = collapse(ts, at, fun=mean)
ts2.index = apply.(tf, ts2.index)
ts2
end
function apply(f::Function, dt)
f(dt)
end
srand(1234)
idx=DateTime(2010,1,1):Dates.Hour(1):DateTime(2017,1,1)-Dates.Hour(1)
idx = collect(idx) + Dates.Second(1)
n=length(idx)
price=100+cumsum(2*(rand(n)-0.5))
volume=rand(n)*1000
ts = TS([price volume], idx, [:price, :volume])
ts_price = ts[:price]
println(ts_price)
tf = dt -> floor(dt, Dates.Hour(4))
println(mean(resample(ts_price, tf)))
#tf = TimeFrame("4H")
#println(mean(resample(ts_price, tf)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment