This algo is dollar neutral buying underperforming bond etf's relative to their averages and selling outperforming bond etf's relative to their averages and hedging with spy. Exits when price meets average and each trade value is 2.5% of portfolio cash value. Please add suggestions.
import pytz
from itertools import imap
import numpy as np
import math
def initialize(context):
context.sec=[ sid(34846),sid(23881),sid(34831),sid(33147),sid(35175),sid(35927),sid(34793),
sid(33541),sid(34830),sid(32984),sid(33649)]
context.spy=sid(8554)
context.max_notional = 1000000.1
context.min_notional = -1000000.0
set_commission(commission.PerShare(cost=.0035))
def handle_data(context, data):
sp=data[context.spy].close_price
hi=data[context.spy].high
lo=data[context.spy].low
vwaps=data[context.spy].vwap(2)
mavgs=data[context.spy].mavg(20)
current_share = context.portfolio.positions[context.spy].amount
cash=context.portfolio.positions_value
pam=(sp+hi+lo+vwaps+mavgs)/5
c=context.portfolio.cash
for stock in context.sec:
price=data[stock].close_price
mavg=data[stock].mavg(20)
vwap=data[stock].vwap(5)
high=data[stock].high
low=data[stock].low
vwap=data[stock].vwap(2)
buy =(context.portfolio.cash * .025)/price
buys =(context.portfolio.cash * .025)/sp
pamo=(price+high+low+vwap+mavg)/5
current_shares = context.portfolio.positions[stock].amount
do=cash+c
if price>pamo :
order(stock,-buy)
order(sid(8554),buys)
if price<pamo :
order(stock,buy)
order(sid(8554),-buys)
if price==pamo:
order(stock,-1*current_shares)
order(sid(8554),-1*current_share)
if sp==pam:
order(stock,-1*current_shares)
order(sid(8554),-1*current_share)
if do <1000000:
order(stock,-1*current_shares)
order(sid(8554),-1*current_share)