Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Help with VWAP

Attempting to get a VWAP of the current day and buy/sell based on price crossing over VWAP. What am I doing wrong?

1 response

try this

from quantopian.algorithm import attach_pipeline, pipeline_output  
from quantopian.pipeline import Pipeline  
from quantopian.pipeline.data.builtin import USEquityPricing  
from quantopian.pipeline.factors import VWAP

def initialize(context):  
    context.aapl = sid(24)  

    pipe = Pipeline()  
    attach_pipeline(pipe, 'vwap_calc')  
    VWAP_1 = VWAP(window_length=1)  
    pipe.add(VWAP_1, 'vwap')  



def before_trading_start(context, data):  
    # Our pipeline output includes all securities in the universe.  
    context.pipe_output = pipeline_output('vwap_calc')  
    # We narrow it down to just the security we are interesting in.  
    context.pipe_output = context.pipe_output[context.pipe_output.index == context.aapl]  
def handle_data(context,data):  
    # Here we're getting the volume-weighted-average-price of the security  
    # defined above, in the context.aapl variable, from the pipeline output.  
    vwap = context.pipe_output.iloc[0]['vwap']  
    # We need a variable for the current price of the security to compare to  
    # the average.  
    price = data.current(context.aapl, 'price')  
    if context.aapl in context.portfolio.positions:  
        if price < vwap:  
            order(context.aapl,100)  
    if context.aapl not in context.portfolio.positions:  
        if price > vwap:  
            order(context.aapl,100)