Skip to content

Instantly share code, notes, and snippets.

@raddy
Created January 23, 2014 16:43
Show Gist options
  • Select an option

  • Save raddy/8582053 to your computer and use it in GitHub Desktop.

Select an option

Save raddy/8582053 to your computer and use it in GitHub Desktop.
rolling_volume in cython etc
%%cython
import numpy as np
import pandas as pd
import sys
cimport cython
cimport numpy as np
ctypedef np.double_t DTYPE_t
cdef extern from "math.h":
bint isnan(double x)
cdef inline double double_max(double a, double b): return a if a >= b else b
cdef inline double double_min(double a, double b): return a if a <= b else b
cdef inline double abz(double a) : return a if a >= 0. else -1 * a
cdef inline long labz(long a) : return a if a >= 0 else -1 * a
def wavgDeltas(np.ndarray[long,ndim=1] prices,np.ndarray[long,ndim=1] sizes, long deltas):
cdef:
long plen = prices.shape[0],count,i,j,sz
np.ndarray[double, ndim=1] res = np.zeros(plen, dtype=np.double)
double avg_price
for i from 0<=i<plen:
count = 0
avg_price =0
for j from i>=j>=0:
sz = labz(sizes[j])
if sz>0: #trade!
count+=sz
avg_price+=prices[j]*sz
if count > deltas:
avg_price -= (prices[j] * (count-deltas))
count = deltas
j=-1
if count>0:
avg_price/=count
res[i] = avg_price
return res
def rolling_volume(np.ndarray[long,ndim=1] times, np.ndarray[long,ndim=1] sizes, long time_in_ns):
cdef:
long t_len = times.shape[0]
long s_len = sizes.shape[0]
long i =0, window_start, j, tots_volume
np.ndarray[long, ndim=1] res = np.zeros(t_len, dtype=long)
assert(t_len==s_len)
for i in range(1,t_len):
window_start = times[i] - time_in_ns
j = i
tots_volume=0
#climb back to find the start of the window
while times[j]>= window_start and j>=0:
j-=1
j+=1
#now step FORWARD through to calculate the streaks
while j<=i:
tots_volume+=sizes[j]
j+=1
res[i] = tots_volume
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment