Good afternoon everybody. I am new to Quantopian and got started on this yesterday. I think that what the algo does now is that it gets long (all the money in the account) when the 50 sma crosses above the 200sma (selling those shares when the 50 sma crosses below the 200 sma) and when the 50 sma crosses below the 200 sma, it shorts 10000 shares of SPY and covers when the 50 sma crosses back above the 200 sma.
One of the problems I am having is that I would like for the algo to short the total account value (similar to when it gets long the entire account value--I have that named bull_shares) instead of the 10,000 shares I have it shorting now. I tried a similar approach naming it bear_shares and having it equal
-round(context.portfolio.cash/price,0)
but that proved fruitless.
Second, I seem to be having log file problems as well. I notice that in the beginning the log files work great, it gets long X shares and sells X shares on Y date then Shorts Z shares on Y date. But then after a few entries I notice it having 2 buy entries in a row (which shouldn't be possible without a sell and short order in between). Any comments or help would be greatly appreciated guys, thank you.
Also, I am very new to python as well, so if my code is off in any obvious manner, I apologize ahead of time :-)
John
must denote two seperate states for long and short, called context.bull and
context.bear. Or else the algo's long and short side will overlap. Couldn't think
of a better way to do this.
def initialize(context):
context.sid = sid(8554)
context.bull = False
context.bear = False
context.spy = sid(8554)
context.sid_names = {8554: "SPY"}
def handle_data(context, data):
short = data[context.sid].mavg(8)
mid = data[context.sid].mavg(21)
long = data[context.sid].mavg(50)
mlong = data[context.sid].mavg(100)
slong = data[context.sid].mavg(200)
price = data[context.sid].price
bull_shares = round(context.portfolio.cash/price,0)
sid_name = context.sid_names
#this is the 'long' version of the algo
if (long > slong) and not context.bull:
order(context.sid, bull_shares)
context.bull_shares = bull_shares
context.bull = True
log.info("BOT " + str(bull_shares) + " shares of " + str(sid_name) + " at " + str(price) + ".")
if (long < slong) and context.bull:
order(context.sid, -context.bull_shares)
context.bull = False
log.info("SOLD " + str(-context.bull_shares) + " shares of " + str(sid_name) + " at " + str(price) + ".")
#this is where the 'long' algo ends
record(short_mavg = short,
long_mavg = long,
mid_mavg = mid,
slong_mavg = slong,
spy_price = price)
#this is the 'short' version of the algo
if (long < slong) and not context.bear:
order(context.sid, -10000)
context.bear = True
log.info("SHT 10000 shares of " + str(sid_name) + " at " + str(price) + ".")
if (long > slong) and context.bear:
order(context.sid, 10000)
context.bear = False
log.info("COVRD 10000 shares of "+ str(sid_name) + " at " + str(price) + ".")
#this is where the 'short' algo ends