Hello, I'm attempting to write a script using the Antonacci's Dual Momentum strategy. However, I'm a little stuck and I need your help.
How can I write a sell condition, that if my top momentum pick already exists in context.portfolio.positions, do not liquidate the portfolio? Inversely, if my top momentum pick does not exist in context.portfolio.postisions liquidate the portfolio.
Code below:
from operator import itemgetter
def initialize(context):
context.stocks = symbols('XLY', # XLY Consumer Discrectionary SPDR Fund
'XLF', # XLF Financial SPDR Fund
'XLK', # XLK Technology SPDR Fund
'XLE', # XLE Energy SPDR Fund
'XLV', # XLV Health Care SPRD Fund
'XLI', # XLI Industrial SPDR Fund
'XLP', # XLP Consumer Staples SPDR Fund
'XLB', # XLB Materials SPDR Fund
'XLU') # XLU Utilities SPRD Fund
schedule_function(Momentum_Sell,
date_rule=date_rules.month_end(days_offset=3),
time_rule=time_rules.market_close(minutes=3))
schedule_function(Momentum_Buy,
date_rule=date_rules.month_end(),
time_rule=time_rules.market_close(minutes=3))
def handle_data(context, data):
pass
######## MA ALGO START ###################
# ma1 = data[stock].mavg(50)
# ma2 = data[stock].mavg(200)
#
#
# if ma1 > ma2:
# order_target_percent(stock, 0.11)
#
# elif ma1 < ma2:
# order_target_percent(stock, -0.11)
######## MA ALGO STOP ####################
######## MOMENTUM LIST START #############
def Momentum_Algo(context, data):
TopMom = []
price_history = history(250,'1d','price')
for stock in context.stocks:
pct_change = (price_history[stock].ix[-1] - price_history[stock].ix[0]) / price_history[stock].ix[0]
TopMom.append([stock, pct_change])
TopMom = sorted(TopMom, key=itemgetter(1), reverse=True)
TopMom = TopMom[0:1]
return TopMom
######## MOMENTUM LIST STOP ##############
######## MOMENTUM ALGO START #############
def Momentum_Sell(context, data):
pass
TopMom = Momentum_Algo(context, data)
top_stock = TopMom[0:1]
#for l in TopMom:
for stock in context.portfolio.positions:
if stock in top_stock:
pass
else:
order_target_value(stock, 0)
def Momentum_Buy(context, data):
TopMom = Momentum_Algo(context, data)
for l in TopMom:
top_stock = l[0]
if top_stock in data and context.portfolio.positions[top_stock].amount <= 0:
order_target_percent(top_stock, 1)
# if context.portfolio.positions not in data:
# order_target_value(context.portfolio.positions, 0)
######## MOMENTUM ALGO STOP ##############