Could anybody take a second to help me troubleshoot? The issue is that the comparisons are referencing the entire array of stocks rather than just the current stock. I'm not sure how to force it to only check the current security. Below is the code I am using:
import talib
import numpy as np
import pandas as pd
# Setup our variables
def initialize(context):
context.stocks = [sid(24),sid(3766),sid(3149),sid(45451),sid(12107)]
def handle_data(context, data):
#calculate price history
prices = history(20, '1d', 'price')
#loop through investable universe
for stock in context.stocks:
current_position = context.portfolio.positions[stock].amount
price = data[stock].price
#calculate bollinger bands
upper, middle, lower = talib.BBANDS(prices[stock], timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)
#Evaluate current shorts
if (current_position < 0) and (price <= (upper+middle)/2):
order_target_percent(stock, 0)
elif (current_position > 0) and (price >= (lower+middle)/2):
order_target_percent(stock, 0)
#if no position and above upper band, initiate short
elif current_position == 0:
if price > upper:
order_target_percent(stock, -1 * min(context.portfolio.cash,context.portfolio.portfolio_value*.1))
#if no posiiton and below lower band, initiate long
elif price < lower:
order_target_percent(stock, min(context.portfolio.cash,context.portfolio.portfolio_value*.1))