Hello,
I am trying to adapt this algorithm from working with only one stock to working with either one stock or many stocks but cannot figure out exactly how to accomplish this. Thanks for the help. Here is the code for the one stock only version:
# Put any initialization logic here. The context object will be passed to
# the other methods in your algorithm.
def initialize(context):
context.security = sid(20541)
# Will be called on every trade event for the securities you specify.
def handle_data(context, data):
print(data)
MA1 = data[context.security].mavg(50)
MA2 = data[context.security].mavg(100)
current_price = data[context.security].price
current_positions = context.portfolio.positions[context.security].amount
cash = context.portfolio.cash
if (MA1 > MA2) and current_positions == 0:
number_of_shares = int(cash/current_price)
order(context.security, number_of_shares)
log.info("buying shares")
elif (MA1 < MA2) and current_positions != 0:
order_target(context.security, 0)
log.info("selling shares")
record(MA1 = MA1, MA2 = MA2, Price = current_price)
Thanks,
Nick