Skip to content

Instantly share code, notes, and snippets.

@fawce
Created January 8, 2012 14:07
Show Gist options
  • Save fawce/1578464 to your computer and use it in GitHub Desktop.
Save fawce/1578464 to your computer and use it in GitHub Desktop.
Example Algorithm for Quantopian - VWAP
vwapMap = {}
class DailyVWAP:
"""A class that tracks the volume weighted average price
based on tick updates."""
def __init__(self, sid, period_length):
self.sid = sid
self.ticks = []
self.value = 0.0
self.period_length = period_length
def update(self,curTick):
self.ticks.append(curTick)
self.ticks = [x for x in self.ticks if (x.dt - curTick.dt).days <= self.period_length]
flux = 0.0
volume = 0
for tick in self.ticks:
flux += tick.volume * tick.price
volume += tick.volume
if(volume != 0):
self.value = flux / volume
else:
self.value = None
set_filter([19656])
def handle_events(eventQueue):
for curTick in eventQueue:
vwap = None
if vwapMap.has_key(curTick.sid):
vwap = vwapMap[curTick.sid]
else:
vwap = DailyVWAP(curTick.sid, 3) #period is 3 days
vwap.update(curTick)
if(vwap == None or vwap.value == None):
continue
if curTick.price > vwap.value:
order(curTick.sid,100)
elif curTick.price < vwap.value * (0.995):
order(curTick.sid,-100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment