Back to Community
VWAP Example

Hello everyone,

I am very new to quantopian and trying to learn how to code in it. I'm an industrial engineering student, graduating next semester and trying to enter the field of data science. I backtested an already written vwap code from 2016-11-16 to 2016-12-01 with $100,000 initial capital. But i do not completely understand the backtest results as I dont have prior programming or finance experience/knowledge. Can someone please explain the code to me and the result summary tab. It would be of great help. I am working on a project and my goal is to built an algorithm based on the concepts of co-integration and pairs trading. I did see the lecture videos on co-integration and pairs trading and also went through the sample pairs trading example. But again, couldn't understand much. It would be really helpful if someone could explain this example atleast so I could proceed further.

Thank you.

Looking forward.

Clone Algorithm
104
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import AverageDollarVolume, Returns


def initialize(context):
    # AAPL, MSFT, and SPY
    context.securities = [sid(24), sid(5061), sid(8554)]

def vwap(prices, volumes):
    return (prices * volumes).sum() / volumes.sum()

def handle_data(context, data):
    hist = data.history(context.securities, ["price", "volume"], 1, '1d')

    #vwap_15 = vwap(hist["price"][-15:], hist["volume"][-15:])
    vwap1 = vwap(hist["price"], hist["volume"])

    for s in context.securities:
        if "price" < vwap1[s]:
            order_target_percent(sid(24), 1.0) 
        else:
            order_target_percent(sid(24), -1.0)
There was a runtime error.
2 responses

I am not sure that if statement is doing what you think it is. Comparing a string "price" to be less than a variable that is an float does not seem like the correct logic?

No It's not the correct thing to do, you just need to replace 'price' with the actual price of the stock at that moment which you can get doing data.current(stock,'price'). So the full code would be:

for s in context.securities:  
        current_price  = data.current(s,'price')  
        if current_price < vwap1[s]:  
            order_target_percent(s, 1.0)  
        else:  
            order_target_percent(s, -1.0)