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, 'SMA_period_short':15, 'SMA_period_long':60, 'RSI_period':60, '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(context): context.lookback = 12 * 21 context.offset = 1 * 21 context.min_volume = 1E8 context.max_size = 10 context.min_size = 5 context.weight = 0 context.universe = [] if context.broker.name == 'regT': context.hedge = symbol('SPY') elif context.broker.name == 'nse-backtest': context.hedge = symbol('NIFTY-I') else: raise ValueError(f'this broker not supported:{context.broker.name}') context.hedge_threshold = 10000 schedule_function(strategy, date_rules.month_start(days_offset=0), time_rules.market_close(hours=2, minutes=30)) attach_pipeline(make_strategy_pipeline(context), name='strategy_pipeline') schedule_function(hedge, date_rules.every_day(), time_rules.market_open(hours=0, minutes=30)) schedule_function(hedge, date_rules.every_day(), time_rules.market_close(hours=0, minutes=30))
def initialize(context): """ this function is called once at the start of the execution. """ context.assets = [symbol('AAPL'), symbol('KO')] context.take_profit = 0.0005 context.stop_loss = 0.0005 context.traded = False context.entry_price = {} context.order_monitors = {} context.data_monitors = {}
def generate_signals(context, data): try: pipeline_results = pipeline_output('strategy_pipeline') except NoFurtherDataError: context.weights = {} return # return if the filtered universe is too short n = int(context.params['universe']) rets = pipeline_results.dropna() if len(rets) < n: context.weights = {} return # select top n assets as universe by liquidity factor rets = rets.sort_values('liquidity') rets = rets.iloc[-n:] # calculate the 1-week broad market return spx = data.history(symbol('SPY'),'close',10,'1d').dropna() mkt_ret = spx[-1]/spx[-5] - 1 # calculate mean reversion weights rets['weight'] = -(rets['momentum']-mkt_ret) rets['weight'] = rets['weight']/rets['weight'].abs().sum() context.weights = rets['weight'].to_dict()
def create_universe(context): """ add list of stocks to create trading universe. """ stocks = ['MSFT','AAPL','AMZN','FB','GOOG','BRK.B','JPM','JNJ', 'XOM','V','BAC','INTC','PG','CSCO','DIS','HD','VZ', 'CVX','MA'] context.universe = [symbol(stock) for stock in stocks]
def initialize(context): """ this function is called once at the start of the execution. """ context.universe = [symbol('NTPC')] context.ordered = {asset: False for asset in context.universe} context.target = {asset: 0 for asset in context.universe} context.stop = {asset: 0 for asset in context.universe} context.data_monitors = {}
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('AUD/USD'), symbol('EUR/CHF'), symbol('EUR/JPY'), symbol('EUR/USD'), symbol('GBP/USD'), symbol('NZD/USD'), symbol('USD/CAD'), symbol('USD/CHF'), symbol('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 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('AMZN'), symbol('FB'), symbol('AAPL'), symbol('GOOGL'), symbol('NFLX'), ] # 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))
def initialize(context): """ this function is called once at the start of the execution. """ context.asset = symbol('EUR/USD') context.take_profit = 0.005 context.stop_loss = 0.005 context.traded = False context.entry_price = None context.exit_price = None
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]) # schedule agent weights updates schedule_function(update_agent_weights, date_rules.week_start(), time_rules.market_close())
def initialize(context): """ function to define things to do at the start of the strategy """ context.x = symbol('AMBUJACEM') context.y = symbol('ACC') 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 = 200 # used for zscore calculation context.z_window = 100 # Call strategy function on the first trading day of each week at 10 AM schedule_function(pair_trading_strategy, date_rules.week_start(), time_rules.market_open(minutes=30))
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('GBP/USD') context.y = symbol('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)) # 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.long_portfolio = [ symbol('DIVISLAB'), symbol('SUNPHARMA'), symbol('MARUTI'), symbol('AMARAJABAT'), symbol('BPCL'), symbol('BAJFINANCE'), symbol('HDFCBANK'), symbol('ASIANPAINT'), symbol('TCS') ] # 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))
def initialize(context): """ A function to define things to do at the start of the strategy """ # universe selection context.long_portfolio = [ symbol('AMZN'), symbol('AAPL'), symbol('WMT'), symbol('MU'), symbol('BAC'), symbol('KO'), symbol('BA'), symbol('AXP') ] # 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))
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('AUD/USD'): 1, symbol('EUR/USD'): 1, symbol('GBP/USD'): 1, symbol('NZD/USD'): 1, symbol('USD/CAD'): -1, symbol('USD/CHF'): -1, symbol('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))
def initialize(context): context.universe = [symbol("AAPL"), symbol("MSFT")]
def initialize(context): context.lookback = 12*21 context.offset = 1*21 context.size = 5 context.weight = 0 context.candidates = [] context.universe = [ symbol('SPY'), # large cap symbol('QQQ'), # tech symbol('VUG'), # growth symbol('QUAL'), # quality symbol('MTUM'), # momentum symbol('IWM'), # small cap symbol('USMV'), # min vol symbol('HDV'), # dividend symbol('VEU'), # world equity symbol('VWO'), # EM equity symbol('DBC'), # commodities symbol('USO'), # oil symbol('GLD'), # gold symbol('AGG'), # bonds symbol('TIP'), # inflation ] attach_pipeline(make_strategy_pipeline(context), name='strategy_pipeline') schedule_function(rebalance, date_rules.month_start(days_offset=0), time_rules.market_close(hours=2, minutes=30))
def initialize(context): context.t1 = pd.Timestamp.now() context.asset = symbol('NIFTY-I')
def initialize(context): context.asset = symbol('MARUTI') context.order_func = order_target context.freq = 60 context.bar_count = 0