I'm getting the following error, While trying to run my code below.
I would really appreciate any help. Though I have checked several things already. Since, I'm new to Python. I thought maybe I'm missing something serious.
Runtime exception: KeyError: Equity(24, symbol='AAPL', asset_name='APPLE INC', exchange='NASDAQ GLOBAL SELECT MARKET', start_date=Timestamp('1993-01-04 00:00:00+0000', tz='UTC'), end_date=Timestamp('2015-08-24 00:00:00+0000', tz='UTC'), first_traded=None)
Blockquote
import numpy as np
import pandas as pd
def initialize(context):
set_universe(universe.DollarVolumeUniverse(97, 100))
global Stock_Trading_Signal
#Global variable for each stock (dictionary), +1 if long in that stock or -1 if short in that stock
Stock_Trading_Signal = {}
global Stock_Trading_Price
#Global variable for each stock (dictionary), Holding the trading price. To check when our target for that position is met.
Stock_Trading_Price = {}
schedule_function(Daily_Rebalance, date_rule = date_rules.every_day(), time_rule = time_rules.market_open())
def Daily_Rebalance(context, data):
pass
def handle_data(context, data):
global Stock_Trading_Signal
global Stock_Trading_Price
Stop_Price = 0
#Stop Loss Price Variable
for stock in data:
if data[stock].mavg(45) > 1.025* data[stock].mavg(9):
# If Long Moving average is higher than short moving average
Stop_Price = data[stock].price * (1.015)
order_target_percent(stock, -0.05, style=StopOrder(Stop_Price))
Stock_Trading_Signal[stock] = -1
# Global Dictionary Variable to identify either long (+1) or Short (-1) Position
Stock_Trading_Price[stock] = data[stock].price
# Global Dictionary Variable. Holding the trading price. Used later to exit this trade, when our target for this trade is met
if data[stock].mavg(9) > 1.025* data[stock].mavg(45):
# If Short Moving average is higher than Long moving average
Stop_Price = data[stock].price * (0.985)
order_target_percent(stock, 0.05, style=StopOrder(Stop_Price))
Stock_Trading_Signal[stock] = 1
# Global Dictionary Variable to identify either long (+1) or Short (-1) Position
Stock_Trading_Price[stock] = data[stock].price
# Global Dictionary Variable. Holding the trading price. Used later to exit this trade, when our target for this trade is met
if context.portfolio.positions[stock].amount != 0:
#If We re Holding a Position in the stock
if Stock_Trading_Signal[stock] < 0:
#If We are holding a Short Position
if data[stock].price < Stock_Trading_Price[stock]*0.0985:
#If our target (1.5%) is met
order_target(stock,0)
#Exit complete trading position for this stock
elif Stock_Trading_Signal[stock] > 0:
#If We are holding a Long Position
if data[stock].price > Stock_Trading_Price[stock]*1.015:
#If our target (1.5%) is met
order_target(stock,0)
#Exit complete trading position for this stock