I'm trying to make a simple moving average algorithm where if the moving average of two stocks(apple and google) are good, it will buy them. However when I backtest it, the algorithm doesn't end up buying anything and it has 0.00% returns. Does anyone know what I'm doing wrong? Thanks!
import quantopian.algorithm as algo
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.filters import QTradableStocksUS
def initialize(context):
"""
Called once at the start of the algorithm.
"""
context.security1 = symbol('GOOG')
context.security2 = symbol('AAPL')
def handle_data_spy(context, data):
"""
Called every minute.
"""
price_hist1 = data.history(context.security1, 'price', 50, '1d')
ma1 = price_hist1.mean()
price_hist2 = data.history(context.security1, 'price', 200, '1d')
ma2 = price_hist2.mean()
price_hist3 = data.history(context.security2, 'price', 50, '1d')
ma3 = price_hist3.mean()
price_hist4 = data.history(context.security2, 'price', 200, '1d')
ma4 = price_hist4.mean()
current_price1 = data[context.security1].price
current_positions1 = context.portfolio.positions[symbol('GOOG')].amount
current_price2 = data[context.security2].price
current_positions2 = context.portfolio.positions[symbol('AAPL')].amount
cash = context.portfolio.cash
if ma1>ma2 and ma3>ma4 and current_positions == 0:
number_of_shares = int(cash/current_price)
order(context.security1, number_of_shares)
order(context.security2, number_of_shares)
elif ma1<ma2 and ma3<ma4 and current_positions != 0:
order_target(context.security1, 0)
order_target(context.security2, 0)
pass