Any feedback would be much appreciated. Cheers
import math
position_open = False
position_closed = True
postions_bought_price = 0;
def initialize(context):
context.stock = sid()
context.max_notional = 1000000.1
context.min_notional = -1000000.0
set_commission(commission.PerTrade(cost=5))
def handle_data(context, data):
last_sale_price = context.portfolio.positions[sid(24)].last_sale_price
vwap3 = data[context.stock].vwap(1)
vwap9 = data[context.stock].vwap(3)
profit = 0
loss = 0
price = data[context.stock].price
notional = context.portfolio.positions[context.stock].amount * price
global position_open
global position_closed
# When to open buy position
if vwap3 > vwap9*1.025 and position_open == False and position_closed == True and notional < context.max_notional:
#take a position of 20% of available cash
order_value(context.stock, (.2(context.portfolio.cash))
global positions_bought_price #THIS IS LINE 30
global order_quantity
positions_bought_price = last_sale_price
order_quantity = math.floor(((.2(context.portfolio.cash))/positions_bought_price))
position_open = True
position_closed = False
print "Position Opened"
# When to take profit
if last_sale_price > positions_bought_price*1.2 and position_open == True and position_closed == False:
order(context.stock,-orderquantity)
position_open = False
position_closed = True
profit = last_sale_price*order_quantity - positions_bought_price*order_quantity
print "Closed by Take Profit with $%d profit" % (profit)
# When to stop loss
if last_sale_price < positions_bought_price*0.9 and position_open == True and position_closed == False:
order(context.stock,-order_quantity)
position_open = False
position_closed = True
#loss = last_sale_price*order_quantity - positions_bought_price*order_quantity
loss = positions_bought_price*order_quantity - last_sale_price*order_quantity
print "Closed by Stop Loss with $%d loss" % (loss)