Ok the logic is here:
- fetch_csv from google drive
- Using fetch_csv data, when signal == 1 buy next open , 1 minute after open
- Sell position after 'n' day hold at 3 minutes before market close
My attempt at this is below, I am running into date time error on line:
# convert time to EST time
exchange_time = get_datetime('US/Eastern')
and also unassigned signal attribute on line:
def buy(context,data):
if signal == 1 and not context.bought:
Can anyone run this over and offer some guidance?
from quantopian.algorithm import calendars
import pandas as pd
from pytz import timezone
import datetime
# Preview the inported data frame
def preview(df):
log.info(df.head())
return df
def time_lag(df):
# Correct look-ahead bias in mapping data to times
df = df.tshift(1, freq='D')
log.info(' \n %s ' % df.head())
return df
def initialize(context):
# Robinhood settings
set_long_only()
set_commission(commission.PerShare(cost=0, min_trade_cost=0))
context.allocation = 0.95 # Robinhood requires either limit orders or a 5% margin on orders.
# Fetch CSV from external source
fetch_csv('https://docs.google.com/spreadsheets/d/1EoT-AXs4wY88_kEsOkaYVX1KCpnovu4FwUZC1FTw9DQ/pub?gid=262287766&single=true&output=csv', pre_func = preview, post_func=time_lag, usecols=['signal'], date_column = 'Date', symbol='signal')
# Set Symbol to buy
context.etf = symbol('UPRO')
context.last_rebalance = None
context.next_rebalance = None
context.holding_period = 5 #define holding period in days
# Set times to buy and sell
schedule_function(buy, date_rules.every_day(), time_rules.market_open(minutes=1),
half_days=True, calendar=calendars.US_EQUITIES)
schedule_function(sell, date_rules.every_day(), time_rules.market_close(minutes=3),
half_days=True, calendar=calendars.US_EQUITIES)
schedule_function(record_vars,
date_rules.every_day(),
time_rules.market_close())
def handle_data(context, data):
current_signal = data.current('signal', 'signal')
print current_signal
if context.etf in data.fetcher_assets:
record(signal=data.current(context.etf,
'signal'))
print context.etf
# Get the current exchange time in EST timezone:
exchange_time = pd.Timestamp(get_datetime()).tz_convert('US/Eastern')
# Get all open orders.
open_orders = get_open_orders()
# Set buy rule, if 'signal' == 1 from fetch_csv enter buy next open
def buy(context,data):
if (current_signal == 1) not in open_orders and data.can_trade(context.etf):
order_target_percent(context.etf, context.allocation)
security = (symbol('UPRO'))
order_share = context.portfolio.positions[symbol('UPRO')].amount
print("check order_share=",security.symbol," share=",order_share)
context.last_rebalance = exchange_time
context.next_rebalance = context.last_rebalance + \
datetime.timedelta(days=context.holding_period)
# Sell after fixed 'n' days
def sell(context,data):
#time to sell after 5 days and exit position
if context.last_rebalance is not None and exchange_time >= context.next_rebalance:
order_target_percent(context.etf,0.0)
def record_vars(context, data):
# Check how many long and short positions we have.
longs = 0
for position in context.portfolio.positions.itervalues():
if position.amount > 0:
longs += 1
# Record our variables.
record(leverage=context.account.leverage, long_count=longs)
8/22/2017 edited post to reflect change in exchange_time variable