def test_day_after_thanksgiving(self): early_closes = tradingcalendar.get_early_closes( tradingcalendar.start, tradingcalendar.end.replace(year=tradingcalendar.end.year + 1) ) # November 2012 # Su Mo Tu We Th Fr Sa # 1 2 3 # 4 5 6 7 8 9 10 # 11 12 13 14 15 16 17 # 18 19 20 21 22 23 24 # 25 26 27 28 29 30 fourth_friday = datetime.datetime(2012, 11, 23, tzinfo=pytz.utc) self.assertIn(fourth_friday, early_closes) # November 2013 # Su Mo Tu We Th Fr Sa # 1 2 # 3 4 5 6 7 8 9 # 10 11 12 13 14 15 16 # 17 18 19 20 21 22 23 # 24 25 26 27 28 29 30 fifth_friday = datetime.datetime(2013, 11, 29, tzinfo=pytz.utc) self.assertIn(fifth_friday, early_closes)
def test_early_close_independence_day_thursday(self): """ Until 2013, the market closed early the Friday after an Independence Day on Thursday. Since then, the early close is on Wednesday. """ early_closes = tradingcalendar.get_early_closes( tradingcalendar.start, tradingcalendar.end.replace(year=tradingcalendar.end.year + 1) ) # July 2002 # Su Mo Tu We Th Fr Sa # 1 2 3 4 5 6 # 7 8 9 10 11 12 13 # 14 15 16 17 18 19 20 # 21 22 23 24 25 26 27 # 28 29 30 31 wednesday_before = datetime.datetime(2002, 7, 3, tzinfo=pytz.utc) friday_after = datetime.datetime(2002, 7, 5, tzinfo=pytz.utc) self.assertNotIn(wednesday_before, early_closes) self.assertIn(friday_after, early_closes) # July 2013 # Su Mo Tu We Th Fr Sa # 1 2 3 4 5 6 # 7 8 9 10 11 12 13 # 14 15 16 17 18 19 20 # 21 22 23 24 25 26 27 # 28 29 30 31 wednesday_before = datetime.datetime(2013, 7, 3, tzinfo=pytz.utc) friday_after = datetime.datetime(2013, 7, 5, tzinfo=pytz.utc) self.assertIn(wednesday_before, early_closes) self.assertNotIn(friday_after, early_closes)
def initialize(context): # ポートフォリオの中身 context.vxx = {sid(38054): 1.0} context.vxz = {sid(38055): 1.0} context.spy = sid(8554) fetch_csv(vixUrl, symbol='VIX', skiprows=1, date_column='Date', pre_func=addFieldVIX) fetch_csv(vxstUrl, symbol='VXST', skiprows=3, date_column='Date', pre_func=addFieldVXST) fetch_csv(vxvUrl, symbol='VXV', skiprows=2, date_column='Date', pre_func=addFieldVXV) start_date = context.spy.security_start_date end_date = context.spy.security_end_date # コストはとりあえず0 set_slippage(slippage.FixedSlippage(spread=0.00)) set_commission(commission.PerShare(cost=0.0, min_trade_cost=None)) # detect if the market will close early context.early_closes = tradingcalendar.get_early_closes(start_date, end_date).date context.slopes = pd.Series() context.vixprices = pd.Series() context.vivprices = pd.Series() schedule_function(func=ordering_logic, date_rule=date_rules.every_day(), time_rule=time_rules.market_open(minutes=5))
def test_early_close_independence_day_thursday(self): """ Until 2013, the market closed early the Friday after an Independence Day on Thursday. Since then, the early close is on Wednesday. """ early_closes = tradingcalendar.get_early_closes( tradingcalendar.start, tradingcalendar.end.replace(year=tradingcalendar.end.year + 1)) # July 2002 # Su Mo Tu We Th Fr Sa # 1 2 3 4 5 6 # 7 8 9 10 11 12 13 # 14 15 16 17 18 19 20 # 21 22 23 24 25 26 27 # 28 29 30 31 wednesday_before = datetime.datetime(2002, 7, 3, tzinfo=pytz.utc) friday_after = datetime.datetime(2002, 7, 5, tzinfo=pytz.utc) self.assertNotIn(wednesday_before, early_closes) self.assertIn(friday_after, early_closes) # July 2013 # Su Mo Tu We Th Fr Sa # 1 2 3 4 5 6 # 7 8 9 10 11 12 13 # 14 15 16 17 18 19 20 # 21 22 23 24 25 26 27 # 28 29 30 31 wednesday_before = datetime.datetime(2013, 7, 3, tzinfo=pytz.utc) friday_after = datetime.datetime(2013, 7, 5, tzinfo=pytz.utc) self.assertIn(wednesday_before, early_closes) self.assertNotIn(friday_after, early_closes)
def __init__(self, load=None, bm_symbol="^GSPC", exchange_tz="US/Eastern", max_date=None, extra_dates=None): self.prev_environment = self self.bm_symbol = bm_symbol if not load: load = load_market_data self.benchmark_returns, treasury_curves_map = load(self.bm_symbol) self.treasury_curves = pd.DataFrame(treasury_curves_map).T if max_date: self.treasury_curves = self.treasury_curves.ix[:max_date, :] self.full_trading_day = datetime.timedelta(hours=6, minutes=30) self.early_close_trading_day = datetime.timedelta(hours=3, minutes=30) self.exchange_tz = exchange_tz bi = self.benchmark_returns.index if max_date: self.trading_days = bi[bi <= max_date].copy() else: self.trading_days = bi.copy() if len(self.benchmark_returns) and extra_dates: for extra_date in extra_dates: extra_date = extra_date.replace(hour=0, minute=0, second=0, microsecond=0) if extra_date not in self.trading_days: self.trading_days = self.trading_days + pd.DatetimeIndex([extra_date]) self.first_trading_day = self.trading_days[0] self.last_trading_day = self.trading_days[-1] self.early_closes = get_early_closes(self.first_trading_day, self.last_trading_day)
def initialize(context): context.aapl = sid(24) # Initializing your start and end dates to check for early closes start_date = context.aapl.security_start_date end_date = context.aapl.security_end_date context.early_closes = get_early_closes(start_date,end_date).date # Minutes before close that you want to execute your order, so this will execute at 3:55 PM only context.minutes_early = 5 # Builds a queue for all orders to be executed at the end of the day context.order_queue = {}
def initialize(context): context.aapl = sid(24) # Initializing your start and end dates to check for early closes start_date = context.aapl.security_start_date end_date = context.aapl.security_end_date context.early_closes = get_early_closes(start_date, end_date).date # Minutes before close that you want to execute your order, so this will execute at 3:55 PM only context.minutes_early = 5 # Builds a queue for all orders to be executed at the end of the day context.order_queue = {}
def initialize(context): # Define the instruments in the portfolio: context.sidsLongVol = {sid(38054): +1.0} context.sidsShortVol = {sid(40516): +1.0} context.sidsShortSPY = {sid(22887): +1.0} context.sidsLongSPY = {sid(8554): +1.0} context.spy = symbol('SPY') context.hedge = symbol('IWM') context.vxx = symbol('VXX') context.epsilon = .01 context.ivts=[] context.ivts_medianfiltered = [] pipe = Pipeline() attach_pipeline(pipe, 'vix_pipeline') pipe.add(GetVol(inputs=[cboe_vix.vix_close]), 'vix') pipe.add(GetVol(inputs=[cboe_vxv.close]), 'vxv') vxstUrl = 'http://www.cboe.com/publish/scheduledtask/mktdata/datahouse/vxstcurrent.csv' vx1Url = 'http://www.quandl.com/api/v1/datasets/CHRIS/CBOE_VX1.csv' vx2Url = 'http://www.quandl.com/api/v1/datasets/CHRIS/CBOE_VX2.csv' fetch_csv(vxstUrl, symbol='VXST', skiprows=3,date_column='Date', pre_func=addFieldsVXST) fetch_csv(vx1Url, date_column='Trade Date',date_format='%Y-%m-%d', symbol='v1', post_func=rename_col) fetch_csv(vx2Url, date_column='Trade Date',date_format='%Y-%m-%d', symbol='v2', post_func=rename_col) # Calculating the contango ratio of the front and second month VIX Futures settlements context.threshold = 0.90 #contango ratio threshold schedule_function(ordering_logic,date_rule=date_rules.every_day(),time_rule=time_rules.market_open(hours=0, minutes=1)) # Rebalance every day, 1 hour after market open. context.wait_trigger=False context.vixpipe = None start_date = context.spy.security_start_date end_date = context.spy.security_end_date context.algo_hist={} context.returns_df = pd.DataFrame() # Get the dates when the market closes early: context.early_closes = get_early_closes(start_date, end_date).date context.slopes = Series() context.betas = Series()
def __init__( self, load=None, bm_symbol='^GSPC', exchange_tz="US/Eastern", max_date=None, extra_dates=None ): self.prev_environment = self self.bm_symbol = bm_symbol if not load: load = load_market_data self.benchmark_returns, treasury_curves_map = \ load(self.bm_symbol) self.treasury_curves = pd.Series(treasury_curves_map) if max_date: self.treasury_curves = self.treasury_curves[:max_date] self.full_trading_day = datetime.timedelta(hours=6, minutes=30) self.early_close_trading_day = datetime.timedelta(hours=3, minutes=30) self.exchange_tz = exchange_tz bm = None trading_days_list = [] for bm in self.benchmark_returns: if max_date and bm.date > max_date: break trading_days_list.append(bm.date) self.trading_days = pd.DatetimeIndex(trading_days_list) if bm and extra_dates: for extra_date in extra_dates: extra_date = extra_date.replace(hour=0, minute=0, second=0, microsecond=0) if extra_date not in self.trading_days: self.trading_days = self.trading_days + \ pd.DatetimeIndex([extra_date]) self.first_trading_day = self.trading_days[0] self.last_trading_day = self.trading_days[-1] self.early_closes = get_early_closes(self.first_trading_day, self.last_trading_day)
def __init__( self, load=None, bm_symbol='^GSPC', exchange_tz="US/Eastern", max_date=None, extra_dates=None ): self.prev_environment = self self.bm_symbol = bm_symbol if not load: load = load_market_data self.benchmark_returns, treasury_curves_map = \ load(self.bm_symbol) self.treasury_curves = pd.DataFrame(treasury_curves_map).T if max_date: self.treasury_curves = self.treasury_curves.ix[:max_date, :] self.full_trading_day = datetime.timedelta(hours=6, minutes=30) self.early_close_trading_day = datetime.timedelta(hours=3, minutes=30) self.exchange_tz = exchange_tz bm = None trading_days_list = [] for bm in self.benchmark_returns: if max_date and bm.date > max_date: break trading_days_list.append(bm.date) self.trading_days = pd.DatetimeIndex(trading_days_list) if bm and extra_dates: for extra_date in extra_dates: extra_date = extra_date.replace(hour=0, minute=0, second=0, microsecond=0) if extra_date not in self.trading_days: self.trading_days = self.trading_days + \ pd.DatetimeIndex([extra_date]) self.first_trading_day = self.trading_days[0] self.last_trading_day = self.trading_days[-1] self.early_closes = get_early_closes(self.first_trading_day, self.last_trading_day)
def __init__( self, load=None, bm_symbol='^GSPC', exchange_tz="US/Eastern", max_date=None, env_trading_calendar=tradingcalendar, full_performance_results=True ): self.prev_environment = self self.bm_symbol = bm_symbol if not load: load = load_market_data fetch_treasury = full_performance_results self.benchmark_returns, treasury_curves_map = \ load(self.bm_symbol, fetch_treasury) self.treasury_curves = pd.DataFrame(treasury_curves_map).T if max_date: tr_c = self.treasury_curves # Mask the treasury curvers down to the current date. # In the case of live trading, the last date in the treasury # curves would be the day before the date considered to be # 'today'. self.treasury_curves = tr_c[tr_c.index <= max_date] self.exchange_tz = exchange_tz # `tc_td` is short for "trading calendar trading days" tc_td = env_trading_calendar.trading_days if max_date: self.trading_days = tc_td[tc_td <= max_date].copy() else: self.trading_days = tc_td.copy() self.first_trading_day = self.trading_days[0] self.last_trading_day = self.trading_days[-1] self.early_closes = get_early_closes(self.first_trading_day, self.last_trading_day) self.open_and_closes = env_trading_calendar.open_and_closes.loc[ self.trading_days]
def __init__( self, load=None, bm_symbol='^GSPC', exchange_tz="US/Eastern", max_date=None, extra_dates=None ): self.prev_environment = self self.bm_symbol = bm_symbol if not load: load = load_market_data self.benchmark_returns, treasury_curves_map = \ load(self.bm_symbol) self.treasury_curves = pd.DataFrame(treasury_curves_map).T if max_date: self.treasury_curves = self.treasury_curves.ix[:max_date, :] self.full_trading_day = datetime.timedelta(hours=6, minutes=30) self.early_close_trading_day = datetime.timedelta(hours=3, minutes=30) self.exchange_tz = exchange_tz bi = self.benchmark_returns.index if max_date: self.trading_days = bi[bi <= max_date].copy() else: self.trading_days = bi.copy() if len(self.benchmark_returns) and extra_dates: for extra_date in extra_dates: extra_date = extra_date.replace(hour=0, minute=0, second=0, microsecond=0) if extra_date not in self.trading_days: self.trading_days = self.trading_days + \ pd.DatetimeIndex([extra_date]) self.first_trading_day = self.trading_days[0] self.last_trading_day = self.trading_days[-1] self.early_closes = get_early_closes(self.first_trading_day, self.last_trading_day) self.open_and_closes = tradingcalendar.open_and_closes.ix[ self.trading_days]
def __init__( self, load=None, bm_symbol='^GSPC', exchange_tz="US/Eastern", max_date=None, env_trading_calendar=tradingcalendar ): self.prev_environment = self self.bm_symbol = bm_symbol if not load: load = load_market_data self.benchmark_returns, treasury_curves_map = \ load(self.bm_symbol) self.treasury_curves = pd.DataFrame(treasury_curves_map).T if max_date: tr_c = self.treasury_curves # Mask the treasury curvers down to the current date. # In the case of live trading, the last date in the treasury # curves would be the day before the date considered to be # 'today'. self.treasury_curves = tr_c[tr_c.index <= max_date] self.exchange_tz = exchange_tz # `tc_td` is short for "trading calendar trading days" tc_td = env_trading_calendar.trading_days if max_date: self.trading_days = tc_td[tc_td <= max_date].copy() else: self.trading_days = tc_td.copy() self.first_trading_day = self.trading_days[0] self.last_trading_day = self.trading_days[-1] self.early_closes = get_early_closes(self.first_trading_day, self.last_trading_day) self.open_and_closes = env_trading_calendar.open_and_closes.ix[ self.trading_days]
def initialize(context): # Define the instruments in the portfolio: context.sidsLongVol = { sid(38054): +0.98 #,sid(32268): +1.0 } context.sidsShortVol = { sid(40516): +0.98 #,sid(8554): +1.0 } context.stock = symbol('SPY') fetch_csv(vixUrl, symbol='VIX', skiprows=1, date_column='Date', pre_func=addFieldsVIX) fetch_csv(vxstUrl, symbol='VXST', skiprows=3, date_column='Date', pre_func=addFieldsVXST) fetch_csv(vxvUrl, symbol='VXV', skiprows=2, date_column='Date', pre_func=addFieldsVXV) # Define the benchmark (used to get early close dates for reference). context.spy = sid(8554) start_date = context.spy.security_start_date end_date = context.spy.security_end_date # Get the dates when the market closes early: context.early_closes = get_early_closes(start_date, end_date).date context.slopes = Series() schedule_function(ordering_logic, date_rule=date_rules.every_day(), time_rule=time_rules.market_open(hours=0, minutes=1))
def initialize(context): # Define the instruments in the portfolio: context.USStockMkt = sid(22739) context.IntlStockMkt = sid(34385) context.RealEstate = sid(26669) context.NatResources = sid(32201) context.Bonds = sid(33652) # Define the benchmark (used to get early close dates for reference). context.spy = sid(8554) start_date = context.spy.security_start_date end_date = context.spy.security_end_date # Initialize context variables the define rebalance logic: context.rebalance_date = None context.next_rebalance_Date = None context.rebalance_days = 28 context.rebalance_window_start = 10 context.rebalance_window_stop = 15 # Get the dates when the market closes early: context.early_closes = get_early_closes(start_date,end_date).date
def initialize(context): # Define the instruments in the portfolio: context.USStockMkt = sid(22739) context.IntlStockMkt = sid(34385) context.RealEstate = sid(26669) context.NatResources = sid(32201) context.Bonds = sid(33652) # Define the benchmark (used to get early close dates for reference). context.spy = sid(8554) start_date = context.spy.security_start_date end_date = context.spy.security_end_date # Initialize context variables the define rebalance logic: context.rebalance_date = None context.next_rebalance_Date = None context.rebalance_days = 28 context.rebalance_window_start = 10 context.rebalance_window_stop = 15 # Get the dates when the market closes early: context.early_closes = get_early_closes(start_date, end_date).date
def initialize(context): # Define the instruments in the portfolio: context.sidsLongVol = {sid(38054): +1.0} context.sidsShortVol = {sid(40516): +1.0} context.sidsShortSPY = {sid(22887): +1.0} context.sidsLongSPY = {sid(8554): +1.0} context.spy = symbol('SPY') context.hedge = symbol('IWM') context.vxx = symbol('VXX') context.epsilon = .01 context.ivts = [] context.ivts_medianfiltered = [] pipe = Pipeline() attach_pipeline(pipe, 'vix_pipeline') v = Get_VIX() pipe.add(v, 'vix') vixUrl = 'http://www.cboe.com/publish/scheduledtask/mktdata/datahouse/vixcurrent.csv' vxstUrl = 'http://www.cboe.com/publish/scheduledtask/mktdata/datahouse/vxstcurrent.csv' vxvUrl = 'http://www.cboe.com/publish/scheduledtask/mktdata/datahouse/vxvdailyprices.csv' vx1Url = 'http://www.quandl.com/api/v1/datasets/CHRIS/CBOE_VX1.csv' vx2Url = 'http://www.quandl.com/api/v1/datasets/CHRIS/CBOE_VX2.csv' fetch_csv(vixUrl, symbol='VIX', skiprows=1, date_column='Date', pre_func=addFieldsVIX) fetch_csv(vxstUrl, symbol='VXST', skiprows=3, date_column='Date', pre_func=addFieldsVXST) fetch_csv(vxvUrl, symbol='VXV', skiprows=2, date_column='Date', pre_func=addFieldsVXV) fetch_csv(vx1Url, date_column='Trade Date', date_format='%Y-%m-%d', symbol='v1', post_func=rename_col) fetch_csv(vx2Url, date_column='Trade Date', date_format='%Y-%m-%d', symbol='v2', post_func=rename_col) # Calculating the contango ratio of the front and second month VIX Futures settlements context.threshold = 0.90 #contango ratio threshold context.vix_h = [] schedule_function(ordering_logic, date_rule=date_rules.every_day(), time_rule=time_rules.market_open(hours=0, minutes=1)) # Rebalance every day, 1 hour after market open. context.wait_trigger = False context.vixpipe = None start_date = context.spy.security_start_date end_date = context.spy.security_end_date context.algo_hist = {} context.returns_df = pd.DataFrame() # Get the dates when the market closes early: context.early_closes = get_early_closes(start_date, end_date).date context.slopes = Series() context.betas = Series()
def initialize(context): """ Called once at the start of the algorithm. """ # Create list of "triplets" # Each triplet group must be it's own list with the security to be traded as the first security of the list context.security_group = list() context.security_group.append([sid(23921), sid(16581), sid(25752)]) # Create list of only the securities that are traded context.trade_securities = list() context.intraday_bars = dict() context.last = dict() context.stocks = list() for group in context.security_group: # Verify the group has exactly 3 listed securities if len(group) != 3: raise ValueError('The security group to trade {} must have 3 securities.'.format(group[0].symbol)) # Add first security only to the traded list (if not already added) if group[0] not in context.trade_securities: context.trade_securities.append(group[0]) # Loop through all stocks in triplet group for stock in group: # Add stock to context.stocks (if not already added) and create dictionary objects to hold intraday bars/last prices if stock not in context.stocks: context.stocks.append(stock) context.intraday_bars[stock] = [[],[],[],[]] # empty list of lists (for ohlc prices) context.last[stock] = None # set last price to None # Define time zone for algorithm context.time_zone = 'US/Eastern' # algorithm time zone # Define the benchmark (used to get early close dates for reference). context.spy = sid(8554) # SPY start_date = context.spy.security_start_date end_date = context.spy.security_end_date # Get the dates when the market closes early: context.early_closes = get_early_closes(start_date,end_date).date # Create variables required for each triplet context.PT = dict() context.SL = dict() context.Highest = dict() context.Lowest = dict() context.bars_since_entry = dict() context.prof_x = dict() context.entry_price = dict() context.o1 = dict() context.o2 = dict() context.o3 = dict() context.o4 = dict() context.o5 = dict() context.o6 = dict() context.ord1 = dict() context.ord2 = dict() context.max_daily_entries = dict() context.daily_entries = dict() context.max_pnl = dict() context.min_pnl = dict() context.closed_pnl = dict() context.trading_periods = dict() context.status = dict() context.positions_closed = dict() context.exit_at_close = dict() context.time_to_close = dict() context.reset_filter = dict() context.reset_minutes = dict() context.long_position = dict() context.execution_market_close = dict() context.execution_market_open = dict() context.long_on = dict() context.PT_ON = dict() context.SL_ON = dict() context.HH = dict() context.LL = dict() context.profitable_closes = dict() context.max_time = dict() context.position_amount = dict() i = 0 for group in context.security_group: context.Highest[i] = 100000.0 context.Lowest[i] = 0.0 context.bars_since_entry[i] = 0 context.prof_x[i] = 0 context.entry_price[i] = None context.o1[i] = 0 context.o2[i] = 0 context.o3[i] = 0 context.o4[i] = 0 context.o5[i] = 0 context.o6[i] = 0 context.ord1[i] = None context.ord2[i] = None context.daily_entries[i] = 0 context.closed_pnl[i] = 0 # keep track of individual system profits context.status[i] = 'NOT TRADING' # status of the algo: 'NOT TRADING' or 'TRADING' context.positions_closed[i] = False # keep track of when pnl exits are triggered if i == 0: context.execution_market_close[i] = False context.execution_market_open[i] = True context.long_on[i] = 1 # 1 = long, 0 = short context.PT_ON[i] = 0 context.SL_ON[i] = 1 context.HH[i] = 0 context.LL[i] = 0 context.profitable_closes[i] = 1000001 context.max_time[i] = 2 context.position_amount[i] = 40 context.max_daily_entries[i] = 999999 context.max_pnl[i] = 9999999 context.min_pnl[i] = -9999999 context.trading_periods[i] = ['00:00-23:59'] # format: 'HH:MM-HH:MM' context.reset_filter[i] = False # Turns on/off resetting the filter variables context.reset_minutes[i] = 1 # number of minutes after market open to call reset_trade_filters() context.exit_at_close[i] = False # Turns on/off auto exit x minutes before market close context.time_to_close[i] = 1 # minutes prior to market close to exit all positions else: raise ValueError('No input variables were defined for triplet, index # {}'.format(i)) if context.long_on[i]: # long only strategy context.PT[i] = 100000.0 context.SL[i] = 0.0 else: # short only strategy context.PT[i] = 0.0 context.SL[i] = 100000.0 # Update index i i += 1 # Rebalance intraday. context.minute_counter = 0 context.intraday_bar_length = 5 # number of minutes for the end of day function to run # Run my_schedule_task and update bars based on configured inputs above for i in range(1, 390): if i % context.intraday_bar_length == 0: # bar close schedule_function(get_intraday_bar, date_rules.every_day(), time_rules.market_open(minutes=i)) # update bars if True in context.execution_market_close.values(): # check for True in dictionary schedule_function(my_schedule_task, date_rules.every_day(), time_rules.market_open(minutes=i)) if i % context.intraday_bar_length == 1: # bar open if True in context.execution_market_open.values(): # check for True in dictionary schedule_function(my_schedule_task, date_rules.every_day(), time_rules.market_open(minutes=i))