Im having some trouble ironing out this code.
I got errors for IncompatibleHistoryFrequency, syntax and undefined terms. But honestly I am just needing someone to take a second glance over it,
import datetime
import data
import talib
import time
import pytz
from pytz import timezone
import brokers.ib
from brokers.ib import IBExchange
Hi, I really need a hand with syntax and some of the terms I am using, also calling objects of data like the daily gain, and the average gain per day,
def initialize(context):
log.info(str(get_datetime("US/Eastern")) + ": initializing algorithm")
context.stock = sid(8554) # SPY
context.ETFs = sid(42477),sid(42470) # ugaz and dgaz
set_benchmark(context.stock) # comparing against SPY
schedule_function(check_condition,
date_rules.every_day(),
time_rules.market_open(minutes=15),
half_days=True)
schedule_function(sell, date_rules.every_day(),
time_rules.market_close(minutes=45),
half_days=True)
def check_condition(context, data): #will this function actually do what I want it to do?
global ugaz_OP
global ugaz_CP
open_price = history(bar_count=1, frequency='1m', field='open_price')
for ETFs in data:
ugaz_OP = open_price[ETFs][-1] #[-1] pulls latest open value
current_price = history(bar_count=1, frequency='1m', field='price')
for ETFs in data:
ugaz_CP = current_price[ETFs][-1]
if ugaz_CP - ugaz_OP > 0:
order_value(sid(42477), 5000,
style=MarketOrder(exchange=IBExchange.IEX))
elif ugaz_CP - ugaz_OP < 0:
order_value(sid(42470), 5000,
style=MarketOrder(exchange=IBExchange.IEX))
def sell(context, data):
log.info(str(get_datetime("US/Eastern")) + ": selling current holdings of UGAZ and DGAZ")
order_target(sid(42477), 0, style=MarketOrder(exchange=IBExchange.IEX))
order_target(sid(42470), 0, style=MarketOrder(exchange=IBExchange.IEX))
log.info(str(daily_gain) + (cal average daily gain) #need to find out how to log this
def handle_data(context, data):
# my trailing stop loss loop needs a second look
set_trailing_stop(context, data)
for sec in context.ETFs:
if (data[sec].price < context.stop_price[sec.symbol]) and context.portfolio.positions[sec].amount:
log.info(str(get_datetime("US/Eastern")) + ": selling security [" + str(sec.symbol) + "] | current price: " + str(data[sec].price) + " < stop price: " + str(context.stop_price[sec.symbol]))
order_target(sec, 0)
context.stop_price[sec.symbol] = 0
for sec in context.ETFs:
if context.portfolio.positions[sec].amount:
price = data[sec].price
context.stop_price[sec.symbol] = max(context.stop_price[sec.symbol], context.stop_pct * price)
log.info("stop price for " + sec.symbol + " at " + str(context.stop_price[sec.symbol]))