Skip to content

Instantly share code, notes, and snippets.

@fawce
Created January 8, 2012 14:07

Revisions

  1. fawce created this gist Jan 8, 2012.
    41 changes: 41 additions & 0 deletions quantopian_tutorial.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    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)