In the following algo I attempt to log all my transactions for debugging purposes. My logs show that I am buying positive and negative amounts of shares and selling positive and negative amounts of shares. I do not understand how this is possible given the code provided.
Leverage = .95
def initialize(context):
set_symbol_lookup_date('2012-01-01')
set_universe(universe.DollarVolumeUniverse(floor_percentile=50.0, ceiling_percentile=51.0))
schedule_function(HandleExits)
schedule_function(HandleEntries)
def handle_data(context, data):
positions = context.portfolio.positions
record(Leverage = context.account.leverage)
#record(OpenPositions = sum([1 for sid in positions if positions[sid].amount > 0]))
def HandleEntries(context, data):
positions = context.portfolio.positions
openLongPositions = [sid for sid in positions if positions[sid].amount > 0]
eligible = []
for stock in data:
tradeday = data[stock].datetime
current_price = data[stock].price
moving_avg_20 = data[stock].mavg(20)
moving_avg_50 = data[stock].mavg(50)
moving_avg_200 = data[stock].mavg(200)
if moving_avg_50 > moving_avg_200:
if (stock not in openLongPositions and not get_open_orders(stock)):
eligible.append(stock)
eligible = eligible + openLongPositions
eligibleCount = float(len(eligible))
for stock in eligible:
buy_order_id = order_target_percent(stock, (1.0 / eligibleCount) * Leverage)
buy_order = get_order(buy_order_id)
if buy_order:
print "Bought %s shares of %s on %s for %s." % ((buy_order.amount), (stock.symbol), (tradeday.strftime('%m/%d/%y')), (data[stock].price))
def HandleExits(context, data):
for stock in data:
tradeday = data[stock].datetime
current_price = data[stock].price
moving_avg_50 = data[stock].mavg(50)
moving_avg_200 = data[stock].mavg(200)
if (current_price < moving_avg_50):
sell_order_id = order_target_percent(stock, 0.0)
sell_order = get_order(sell_order_id)
if sell_order:
print "Sold %s shares of %s on %s for %s." % ((sell_order.amount), (stock.symbol), (tradeday.strftime('%m/%d/%y')), (data[stock].price))
Also, does anyone know how I could sell a stock that I purchase if it falls 8% below my original purchase price? I'm not sure how to keep track of the purchase price of each stock I buy. A stop loss order is probably the best solution, but I am not sure how to incorporate that into my logic.