def initialize(context): """ A function to define things to do at the start of the strategy """ # set the account currency, only valid for backtests set_account_currency("USD") # universe selection context.short_dollar_basket = { symbol('FXCM:AUD/USD'):1, symbol('FXCM:EUR/USD'):1, symbol('FXCM:GBP/USD'):1, symbol('FXCM:NZD/USD'):1, symbol('FXCM:USD/CAD'):-1, symbol('FXCM:USD/CHF'):-1, symbol('FXCM:USD/JPY'):-1, } # Call rebalance function on the first trading day of each month after 2.5 hours from market open schedule_function(rebalance, date_rules.month_start(days_offset=0), time_rules.market_close(hours=2, minutes=30)) # set trading cost and slippage to zero set_commission(fx=commission.PipsCost(cost=0.00)) set_slippage(fx=slippage.FixedSlippage(0.00))
def initialize(self, window_length=100): """ Slippage was messing up orders, setting to fixed corrected revisit this """ self.set_slippage(slippage.FixedSlippage()) self.buyplot = {sym: [pd.DataFrame()] for sym in sym_list} self.plotmarks = {sym: [pd.DataFrame()] for sym in sym_list} self.trade_log = {sym: 0 for sym in sym_list} self.trade_dates = {sym: {'DATE': []} for sym in sym_list} self.log = { sym: { 'PAIR': [], 'ZSCORE': [], 'ACTION': [], 'SPREAD': [] } for sym in sym_list } self.day_count = 0 self.dates = [] self.actions = {sym: {'ACTION': []} for sym in sym_list} self.ratios = {sym: {'SPREAD': []} for sym in sym_list} self.zscores = {sym: {'ZSCORE': []} for sym in sym_list} self.spreads = {sym: [] for sym in sym_list} self.gain_plot = {sym: {'GAIN': []} for sym in sym_list} self.window_length = window_length self.ols_transform = ols_transform(refresh_period=self.window_length, window_length=self.window_length)
def initialize(context): ''' A function to define things to do at the start of the strategy ''' # universe selection context.universe = [symbol('NIFTY-I'),symbol('BANKNIFTY-I')] # define strategy parameters context.params = {'indicator_lookback':375, 'indicator_freq':'1m', 'buy_signal_threshold':0.5, 'sell_signal_threshold':-0.5, 'SMA_period_short':15, 'SMA_period_long':60, 'RSI_period':300, 'BBands_period':300, 'ADX_period':120, 'trade_freq':15, 'leverage':1} # variable to control trading frequency context.bar_count = 0 # variables to track target portfolio context.weights = dict((security,0.0) for security in context.universe) # set trading cost and slippage to zero set_commission(commission.PerShare(cost=0.0, min_trade_cost=0.0)) set_slippage(slippage.FixedSlippage(0.00)) # create the list of experts as well as the agent controlling them context.advisor = Advisor('bbands_ea',expert_advisor, context.universe) # schedule agent weights updates pass
def initialize(context): context.start_date = trading_start context.agent = agent context.num_trials = 0 context.action = ACTION context.values = deque(maxlen=21) set_commission(commission.PerShare(cost=0.005, min_trade_cost=1.00)) set_slippage(slippage.FixedSlippage(0.00)) context.universe = universe_transform('2018-01-01') schedule_function(rebalance_portfolio, date_rules.week_start(days_offset=trading_day), time_rules.market_open(hours=1)) #schedule_function(cancel_open_orders, date_rules.every_day(), time_rules.market_open()) schedule_function(prime_pipeline, date_rules.week_start(days_offset=trading_day - 1), time_rules.market_close()) context.Factor_weights = ENV.current_node.weights context.weights = None context.run_pipeline = True #We want to run stock selector immediately context.weeks_since_rebalance = -1 attach_pipeline(make_pipeline(context), 'my_pipeline')
def initialize(context): # Set benchmark to short-term Treasury note ETF (SHY) since strategy is dollar neutral set_benchmark(symbol('AAPL')) # Schedule our rebalance function to run at the end of each day. # Modified the timing to 5 mins earlier than the market close to reduce the fail to book warnings # schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_close(minutes=5)) # Try to change it to open and see what happened -- HY schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_open(minutes=5)) # Record variables at the end of each day. # schedule_function(my_record_vars, date_rules.every_day(), time_rules.market_close()) # Get intraday prices today before the close if you are not skipping the most recent data # schedule_function(get_prices,date_rules.every_day(), time_rules.market_close(minutes=10)) # Try to get the price data when the market is opening -- HY # schedule_function(get_prices, date_rules.every_day(), time_rules.market_open(minutes=1)) # Set commissions and slippage to 0 to determine pure alpha set_commission(commission.PerShare(cost=0, min_trade_cost=0)) set_slippage(slippage.FixedSlippage(spread=0)) # Number of quantiles for sorting returns for mean reversion context.nq = 5 # Number of quantiles for sorting volatility over five-day mean reversion period context.nq_vol = 3 # Create our pipeline and attach it to our algorithm. my_pipe = make_pipeline() attach_pipeline(my_pipe, 'my_pipeline')
def initialize(context): """ A function to define things to do at the start of the strategy """ # universe selection context.securities = [symbol('NIFTY-I'), symbol('BANKNIFTY-I')] # define strategy parameters context.params = { 'indicator_lookback': 375, 'indicator_freq': '1m', 'buy_signal_threshold': 0.5, 'sell_signal_threshold': -0.5, 'ROC_period_short': 30, 'ROC_period_long': 120, 'BBands_period': 300, 'trade_freq': 5, 'leverage': 2 } # variable to control trading frequency context.bar_count = 0 # variables to track signals and target portfolio context.signals = dict((security, 0) for security in context.securities) context.target_position = dict( (security, 0) for security in context.securities) # set trading cost and slippage to zero set_commission(commission.PerShare(cost=0.0, min_trade_cost=0.0)) set_slippage(slippage.FixedSlippage(0.00))
def initialize(self): self.update = raw_input('Update Trends? [y/n]: ') if self.update =='y': for sym in sym_list: self.get_trends(sym,self.update) elif self.update =='n': for sym in sym_list: trend_df = pd.read_csv('trend_data/processed/'+sym_list[0]+'_trend_df.csv',index_col=0,parse_dates=True) self.trend_dfs[sym] = trend_df self.set_slippage(slippage.FixedSlippage()) self.dates = [] self.trends = {sym:[] for sym in sym_list} self.zscores = {sym:[] for sym in sym_list} self.zscores_s = {sym:[] for sym in sym_list} self.chaikin_plot = {sym:[] for sym in sym_list} self.prices = {sym:np.array([]) for sym in sym_list} self.volume = {sym:np.array([]) for sym in sym_list} self.highs = {sym:np.array([]) for sym in sym_list} self.lows = {sym:np.array([]) for sym in sym_list} self.day_count = 0 self.last_order = 0 self.rsi_plot = {sym:np.array([]) for sym in sym_list} self.mfv = {sym:np.array([]) for sym in sym_list} self.stops = {sym:[0,0] for sym in sym_list} #[take,stop] self.buy_plot = {sym:[] for sym in sym_list} self.sell_plot = {sym:[] for sym in sym_list} self.atr_plot = {sym:{'profit':[],'loss':[]} for sym in sym_list} self.gains = {sym:np.array([]) for sym in sym_list} self.mfi_plot = {sym:np.array([]) for sym in sym_list}
def initialize(context): """ API function to define things to do at the start of the strategy. """ # set strategy parameters context.lookback_data = 60 context.lookback_long = 20 context.leverage = 2.0 context.profit_target = 1.0 # reset everything at start daily_reset(context) # create our universe create_universe(context) # schedule calculation at the end of opening range (30 minutes) schedule_function(calculate_trading_metrics, date_rules.every_day(), time_rules.market_open(hours=0, minutes=30)) # schedule entry rules schedule_function(no_more_entry, date_rules.every_day(), time_rules.market_open(hours=1, minutes=30)) # schedule exit rules schedule_function(unwind, date_rules.every_day(), time_rules.market_close(hours=0, minutes=30)) # set trading costs set_commission(commission.PerShare(cost=0.005, min_trade_cost=0.0)) set_slippage(slippage.FixedSlippage(0.00))
def initialize(self): self.set_slippage(slippage.FixedSlippage()) self.dates = [] self.prices = {sym:np.array([]) for sym in feed} self.vratio_plot = {sym:np.array([]) for sym in feed} self.buy_plot = {sym:[] for sym in feed} self.sell_plot = {sym:[] for sym in feed} self.day_count = 0
def initialize(context): """ A function to define things to do at the start of the strategy """ # set the account currency, only valid for backtests set_account_currency("USD") # lot-size (mini-lot for most brokers) context.lot_size = 1000 # universe selection context.securities = [ symbol('FXCM:AUD/USD'), symbol('FXCM:EUR/CHF'), symbol('FXCM:EUR/JPY'), symbol('FXCM:EUR/USD'), symbol('FXCM:GBP/USD'), symbol('FXCM:NZD/USD'), symbol('FXCM:USD/CAD'), symbol('FXCM:USD/CHF'), symbol('FXCM:USD/JPY'), ] # define strategy parameters context.params = { 'indicator_lookback': 375, 'indicator_freq': '1m', 'buy_signal_threshold': 0.5, 'sell_signal_threshold': -0.5, 'SMA_period_short': 15, 'SMA_period_long': 60, 'RSI_period': 60, 'trade_freq': 30, 'leverage': 1, 'pip_cost': 0.00003 } # variable to control trading frequency context.bar_count = 0 context.trading_hours = False # variables to track signals and target portfolio context.signals = dict((security, 0) for security in context.securities) context.target_position = dict( (security, 0) for security in context.securities) # set trading cost and slippage to zero set_commission(fx=commission.PipsCost(cost=context.params['pip_cost'])) set_slippage(fx=slippage.FixedSlippage(0.00)) # set a timeout for trading schedule_function(stop_trading, date_rules.every_day(), time_rules.market_close(hours=0, minutes=31)) # call square off to zero out positions 30 minutes before close. schedule_function(daily_square_off, date_rules.every_day(), time_rules.market_close(hours=0, minutes=30))
def initialize(self, context): context.set_slippage(slippage.FixedSlippage(spread=0)) context.set_commission(commission.PerTrade(cost=0)) context.target_duration = 30 # How long to test strategies for context.num_parents = 4 # Number of parents each new species has context.generation_size = 5 # How many species to generate per generation context.frames = deque(maxlen=70) # Store past frames for past prices context.species = [] # All species are stored here self.new_generation( context) # Create a new generation (starts testing on 70th day)
def initialize(algo, eps=1, window_length=5): algo.stocks = STOCKS algo.tickers = [symbol(ticker) for ticker in algo.stocks] algo.m = len(algo.stocks) algo.price = {} algo.b_t = np.ones(algo.m) / algo.m algo.eps = eps algo.window_length = window_length algo.set_commission(commission.PerShare(cost=0)) algo.set_slippage(slippage.FixedSlippage(spread=0))
def initialize(context): ''' Called once at the start of the strategy execution. This is the place to define things to do at the start of the strategy. ''' # set the account base currency and strategy parameters set_account_currency('USD') context.params = { 'verbose': False, 'leverage': 1, 'rebalance_freq': '15m', 'no_overnight_position': True, 'pip_cost': 0.00008, 'rollover_spread': 0.00, 'BBands_period': 1440, 'SMA_period_short': 150, 'SMA_period_long': 600, 'indicator_lookback': 1440, # max of all lookbacks!!! 'indicator_freq': '1m', 'buy_signal_threshold': 0.5, 'sell_signal_threshold': -0.5 } # define the strategy instruments universe context.universe = [ symbol('FXCM:AUD/USD'), symbol('FXCM:EUR/USD'), symbol('FXCM:NZD/USD'), symbol('FXCM:USD/CAD'), symbol('FXCM:USD/CHF'), ] context.ccy_universe = [ 'AUD', 'CAD', 'CHF', 'EUR', 'GBP', 'JPY', 'NZD', 'USD' ] # function to schedule roll-overs, at 5 PM EST or 9 PM UTC (3 hours before midnight) schedule_function(compute_rollovers, date_rules.every_day(), time_rules.market_close(hours=3, minutes=0)) # set up cost structures, we assume a $1 per $10K all-in cost set_commission(fx=commission.PipsCost(cost=context.params['pip_cost'])) set_slippage(fx=slippage.FixedSlippage(spread=0.00)) # variables to track signals and target portfolio context.signals = dict((security, 0) for security in context.universe) context.weights = dict((security, 0) for security in context.universe) # Call rebalance function, see below under standard helper functions to modify rebalance_scheduler(context) # make the back-test lighter context.perf_tracker.keep_transactions = False context.perf_tracker.keep_orders = False
def initialize(context, asset): context.set_commission(commission.PerShare(cost=0, min_trade_cost=0)) context.set_slippage(slippage.FixedSlippage(spread=0.0)) context.start_date = context.get_datetime() context.asset = context.sid(asset) context.counter = count() # buy 1 first 4 days, close out all last day context.order_amounts = np.repeat(0, len(self.equity_daily_bar_days)) context.order_amounts[0] = 2 # buy 2 lot on first day context.order_amounts[69] = -1 # sell 1 lot on 69th day context.order_amounts[-30] = -1 # close out final lot
def initialize(self,stockA,stockB, window_length=14): self.spreads = [] self.capital_base=10000 self.invested = 0 self.window_length = window_length self.instant_fill=True #Pairslog results are built using EOD data. (I assumed same day of signal) self.stockA=stockA self.stockB=stockB self.posSizeA=self.capital_base self.posSizeB=self.capital_base #I assumed 50% margin for both long and short trades self.set_commission(commission.PerTrade(cost=0)) #Pairslog results do not consider commissions. self.set_slippage(slippage.FixedSlippage(spread=0.0)) #Pairslog results are built using EOD data and do not consider liquidity factor. self.txnumber=0 self.trades = pd.DataFrame()
def initialize(self): self.trend_df = self.get_trends() self.set_slippage(slippage.FixedSlippage()) self.dates = [] self.trends = {sym: [] for sym in sym_list} self.zscores = {sym: [] for sym in sym_list} self.prices = {sym: np.array([]) for sym in sym_list} self.highs = {sym: np.array([]) for sym in sym_list} self.lows = {sym: np.array([]) for sym in sym_list} self.day_count = 0 self.last_order = 0 self.stops = {sym: [0, 0] for sym in sym_list} #[take,stop] self.buy_plot = {sym: [] for sym in sym_list} self.sell_plot = {sym: [] for sym in sym_list} self.atr_plot = {sym: {'profit': [], 'loss': []} for sym in sym_list}
def initialize(context): # slippage model set_slippage(slippage.FixedSlippage(spread=0)) # stock universe - list of tickers securities = ['AAPL', 'ADBE', 'AIG', 'AMGN', 'BA'] # change string list of tickers into asset list using symbol function context.sec_symbols = [symbol(s) for s in securities] print(len(context.sec_symbols)) # schedule functions schedule_function(trade_market_open, date_rules.every_day(), time_rules.market_open()) schedule_function(cancel_open, date_rules.every_day(), time_rules.market_close())
def initialize(context): ''' Called once at the start of the strategy execution. This is the place to define things to do at the start of the strategy. ''' # set the account base currency and strategy parameters set_account_currency('USD') context.params = { 'verbose': False, 'leverage': 2, 'rebalance_freq': 'monthly', 'no_overnight_position': False, 'pip_cost': 0.0001, 'rollover_spread': 0.00, 'positions': 2, 'lookback': 26 * 6 } # define the strategy instruments universe context.universe = [ symbol('FXCM:AUD/USD'), symbol('FXCM:EUR/CHF'), symbol('FXCM:EUR/JPY'), symbol('FXCM:EUR/USD'), symbol('FXCM:GBP/JPY'), symbol('FXCM:GBP/USD'), symbol('FXCM:NZD/USD'), symbol('FXCM:USD/CAD'), symbol('FXCM:USD/CHF'), symbol('FXCM:USD/JPY'), ] context.ccy_universe = [ 'AUD', 'CAD', 'CHF', 'EUR', 'GBP', 'JPY', 'NZD', 'USD' ] # function to schedule roll-overs, at 5 PM EST or 9 PM UTC (3 hours before midnight) schedule_function(compute_rollovers, date_rules.every_day(), time_rules.market_close(hours=3, minutes=0)) # set up cost structures, we assume a $1 per $10K all-in cost set_commission(fx=commission.PipsCost(cost=context.params['pip_cost'])) set_slippage(fx=slippage.FixedSlippage(spread=0.00)) # Call rebalance function, see below under standard helper functions to modify rebalance_scheduler(context)
def initialize(context): """ function to define things to do at the start of the strategy """ # set the account currency, only valid for backtests set_account_currency("USD") # trading pound parity! # this should work after the European sovereign crisis settled down # and before the Brexit noise started (2012-2015) context.x = symbol('FXCM:GBP/USD') context.y = symbol('FXCM:EUR/USD') context.leverage = 5 context.signal = 0 # Trade entry and exit when the z_score is +/- entry_z_score and exit_z_score respectively context.entry_z_score = 2.0 context.exit_z_score = 0.5 # Lookback window context.lookback = 720 # used for zscore calculation context.z_window = 360 # Call strategy function after the London open every day schedule_function(pair_trading_strategy, date_rules.every_day(), time_rules.market_open(hours=9,minutes=30)) # set trading cost and slippage to zero set_commission(fx=commission.PipsCost(cost=0.00)) set_slippage(fx=slippage.FixedSlippage(0.00)) # square off towards to NYC close context.trading_hours = False # set a timeout for trading schedule_function(stop_trading, date_rules.every_day(), time_rules.market_close(hours=0, minutes=31)) # call square off to zero out positions 30 minutes before close. schedule_function(daily_square_off, date_rules.every_day(), time_rules.market_close(hours=0, minutes=30))
def initialize(context): ''' A function to define things to do at the start of the strategy ''' # universe selection context.universe = [symbol('NIFTY-I'), symbol('BANKNIFTY-I')] # define strategy parameters context.params = { 'indicator_lookback': 375, 'indicator_freq': '1m', 'buy_signal_threshold': 0.5, 'sell_signal_threshold': -0.5, 'SMA_period_short': 15, 'SMA_period_long': 60, 'RSI_period': 300, 'BBands_period': 300, 'ADX_period': 120, 'trade_freq': 15, 'leverage': 1 } # variable to control trading frequency context.bar_count = 0 # variables to track target portfolio context.weights = dict((security, 0.0) for security in context.universe) # set trading cost and slippage to zero set_commission(commission.PerShare(cost=0.0, min_trade_cost=0.0)) set_slippage(slippage.FixedSlippage(0.00)) # create the list of experts as well as the agent controlling them expert1 = Advisor('bbands_ea', expert_advisor_1, context.universe) expert2 = Advisor('maxover_ea', expert_advisor_2, context.universe) expert3 = Advisor('rsi_ea', expert_advisor_3, context.universe) expert4 = Advisor('sup_res_ea', expert_advisor_4, context.universe) context.agent = Agent([expert1, expert2, expert3, expert4], 0.35, method=1) # schedule agent weights updates schedule_function(update_agent_weights, date_rules.week_start(), time_rules.market_close())
def initialize(context): attach_pipeline(make_pipeline(), 'data_pipeline') context.technical_indicator_states = {} context.window_length = 7 context.benchmark = deque(maxlen=context.window_length) context.benchmark_asset = symbol('SPY') context.benchmark_assets = symbols('QQQ', 'SPY') #context.classifier = RandomForestClassifier() # Use a random forest classifier context.classifier = DecisionTreeClassifier(max_depth=5, max_leaf_nodes=10) # Clasifier training data context.features = [ 'RSI', 'EMA', 'MACD', 'SMA_5', 'SMA_10', 'bb_lower', 'bb_middle', 'bb_upper' ] context.response = ['Class'] context.X = pd.DataFrame( columns=context.features) # Independent, or input variables context.Y = pd.DataFrame( columns=context.response) # Dependent, or output variable context.prediction = {} # Stores most recent prediction context.tick = 0 context.total_buy = 0 context.positions = None context.position_adjustment_days = 5 # Number of days to wait before adjusting positions context.min_data_points = 500 context.max_data_points = 1500 schedule_function(rebalance, date_rules.every_day(), time_rules.market_open(minutes=1)) schedule_function(record_vars, date_rules.every_day(), time_rules.market_close()) set_benchmark(symbol('SPY')) # Turn off the slippage model set_slippage(slippage.FixedSlippage(spread=0.0)) # Set the commission model (Interactive Brokers Commission) set_commission(commission.PerShare(cost=0.01, min_trade_cost=1.0))
def initialize(context): # Quantopian backtester specific variables set_slippage(slippage.FixedSlippage(spread=0)) set_commission(commission.PerShare(cost=0.01, min_trade_cost=1.0)) context.pairs = [ # STX, WDC KalmanPairTrade(symbol('STX'), symbol('WDC'), initial_bars=300, freq='1m', delta=1e-3, maxlen=300), # CBI, JEC KalmanPairTrade(symbol('CBI'), symbol('JEC'), initial_bars=300, freq='1m', delta=1e-3, maxlen=300), # MAS, VMC KalmanPairTrade(symbol('MAS'), symbol('VMC'), initial_bars=300, freq='1m', delta=1e-3, maxlen=300), # JPM, C KalmanPairTrade(symbol('JPM'), symbol('C'), initial_bars=300, freq='1m', delta=1e-3, maxlen=300), # AON, MMC KalmanPairTrade(symbol('AON'), symbol('MMC'), initial_bars=300, freq='1m', delta=1e-3, maxlen=300), # COP, CVX KalmanPairTrade(symbol('COP'), symbol('CVX'), initial_bars=300, freq='1m', delta=1e-3, maxlen=300), ] context.security_list = [ symbol('STX'), symbol('WDC'), symbol('CBI'), symbol('JEC'), symbol('MAS'), symbol('VMC'), symbol('JPM'), symbol('C'), symbol('AON'), symbol('MMC'), symbol('COP'), symbol('CVX'), ] weight = 1.8 / len(context.pairs) for pair in context.pairs: pair.leverage = weight for minute in range(10, 390, 90): for pair in context.pairs: schedule_function(pair.trading_logic, time_rule=time_rules.market_open(minutes=minute))