def initialize(context):
    # Turn off the slippage model
    set_slippage(slippage.FixedSlippage(spread=0.0))
    # Set the commission model
    set_commission(commission.PerShare(cost=0.01, min_trade_cost=1.0))
    context.day = -1 # using zero-based counter for days
    context.set_benchmark(symbol('DIA'))
    context.assets = []
    print('Setup investable assets...')
    for ticker in asset_tickers:
        #print(ticker)
        context.assets.append(symbol(ticker))
    context.n_asset = len(context.assets)
    context.n_portfolio = 40 # num mean-variance efficient portfolios to compute
    context.today = None
    context.tau = None
    context.min_data_window = 756 # min of 3 yrs data for calculations
    context.first_rebal_date = None
    context.first_rebal_idx = None
    context.weights = None
    # Schedule dynamic allocation calcs to occur 1 day before month end - note that
    # actual trading will occur on the close on the last trading day of the month
    schedule_function(rebalance,
                  date_rule=date_rules.month_end(days_offset=1),
                  time_rule=time_rules.market_close())
    # Record some stuff every day
    schedule_function(record_vars,
                  date_rule=date_rules.every_day(),
                  time_rule=time_rules.market_close())
Ejemplo n.º 2
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))
Ejemplo n.º 3
0
def initialize(context):
    # This code runs once, when the sim starts up
    log.debug('scheduling rebalance and recording')

    set_slippage(slippage.FixedSlippage(spread=0.0))
    set_commission(commission.PerShare(cost=0, min_trade_cost=0))

    schedule_function(func=rebalance,
                      date_rule=date_rules.month_end(),
                      time_rule=time_rules.market_close(minutes=15))

    schedule_function(func=record_daily,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_close())
Ejemplo n.º 4
0
def initialize(context):
    """
    Called once at the start of the algorithm.
    """
    feature_num = 11
    context.orders_submitted = False
    large_num = 9999999
    least_num = 0
    context.n_components = feature_num
    context.security = symbol(SYMBOL)  # Trade SPY
    set_benchmark(symbol(SYMBOL))  # Set benchmarks
    context.model = DecisionTreeClassifier(criterion='entropy',
                                           max_depth=feature_num,
                                           random_state=0)
    context.lookback = 350  # Look back 62 days
    context.history_range = 350  # Only consider the past 400 days' history
    context.threshold = 4.05
    context.longprices = large_num
    context.shortprices = least_num
    set_long_only()
    # Generate a new model every week
    schedule_function(create_model, date_rules.week_end(),
                      time_rules.market_close(minutes=10))
    """
    # Generate a new model every week
    schedule_function(create_model1, date_rules.week_end(), time_rules.market_close(minutes=10))
    """

    # Trade at the start of every day
    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open(minutes=1))
Ejemplo n.º 5
0
    def initialize(self, context):
        if self.verbose: print("Starting the robo advisor")

        # Populate Portfolios
        self.all_portfolios = initialize_portfolio(self.verbose)

        # Set Commission model
        self.initialize_commission(country=self.country, platform=self.trading_platform)

        # Set Slippage model
        set_slippage(slippage.FixedSlippage(spread=0.0))  # assume spread of 0

        # Schedule Rebalancing check
        rebalance_check_freq = date_rules.month_end()
        if (self.rebalance_freq == 'daily'): rebalance_check_freq = date_rules.every_day()
        elif (self.rebalance_freq == 'weekly'): rebalance_check_freq = date_rules.week_end()

        if self.verbose: print('Rebalance checks will be done %s' % self.rebalance_freq)
        schedule_function(
            func=self.before_trading_starts,
            date_rule=rebalance_check_freq,
            time_rule=time_rules.market_open(hours=1))

        # record daily weights at the end of each day
        schedule_function(
            func=record_current_weights,
            date_rule=date_rules.every_day(),
            time_rule=time_rules.market_close()
        )
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(context):
        """ Called once at the start of the algorithm. """

        set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.1))
        set_commission(commission.PerShare(cost=0.01, min_trade_cost=1.00))
        set_max_leverage(1.0)

        # Rebalance every day, 1 hour after market open.
        schedule_function(
            context.my_rebalance,
            date_rules.every_day(),
            time_rules.market_open(hours=1)
        )

        # Close all positions every day, 30 minutes before market close.
        schedule_function(
            context.close_positions,
            date_rules.every_day(),
            time_rules.market_close(minutes=30)
        )

        # Create risk manager
        context.risk_manager = RiskManager(context, daily_risk)

        # Create our dynamic stock selector.
        attach_pipeline(context.make_screener(), 'stock_screener')
Ejemplo n.º 8
0
def initialize(context):
    """
    Called once at the start of the algorithm.
    """
    feature_num = 11
    context.orders_submitted = False
    large_num = 9999999
    least_num = 0
    context.n_components = feature_num
    context.security = symbol(SYMBOL)  # Trade SPY
    set_benchmark(symbol(SYMBOL))  # Set benchmarks
    context.model = SVC(kernel='rbf', tol=1e-3, random_state=0, gamma=0.2, C=10.0, verbose=True)  # 8.05 for SVM model
    context.lookback = 350  # Look back 62 days
    context.history_range = 350  # Only consider the past 400 days' history
    context.threshold = 4.05
    context.longprices = large_num
    context.shortprices = least_num
    set_long_only()
    # Generate a new model every week
    schedule_function(create_model, date_rules.week_end(), time_rules.market_close(minutes=10))
    """
    # Generate a new model every week
    schedule_function(create_model1, date_rules.week_end(), time_rules.market_close(minutes=10))
    """

    # Trade at the start of every day
    schedule_function(rebalance, date_rules.every_day(), time_rules.market_open(minutes=1))
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))
Ejemplo n.º 10
0
def initialize(context):
    """
    Called once at the start of the algorithm.
    """

    set_slippage(slippage.FixedSlippage(spread=0.00))
    set_commission(commission.PerShare(cost=0, min_trade_cost=0))

    schedule_function(rebalance, TRADE_FREQ,
                      date_rules.every_day(),
                      time_rules.market_open(hours=1, minutes=30),
    )

    schedule_function(record_vars, date_rules.every_day(),
                      time_rules.market_close())

    ml_pipeline = make_ml_pipeline(universe,
                                   n_forward_days=N_FORWARD_DAYS,
                                   window_length=TRAINING_PERIOD)

    # Create our dynamic stock selector.
    attach_pipeline(ml_pipeline, 'ml_model')

    context.past_predictions = {}
    context.ic = 0
    context.rmse = 0
    context.mae = 0
    context.returns_spread_bps = 0
Ejemplo n.º 11
0
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))
Ejemplo n.º 12
0
def initialize(context):
    """
        A function to define things to do at the start of the strategy
    """

    # universe selection
    context.long_portfolio = [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))
Ejemplo n.º 13
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
Ejemplo n.º 14
0
def initialize(context):
    """
    Called once at the start of the algorithm.
    """
    feature_num = 11
    context.orders_submitted = False
    large_num = 9999999
    least_num = 0
    context.n_components = feature_num
    context.security = symbol(SYMBOL)  # Trade SPY
    set_benchmark(symbol(SYMBOL))  # Set benchmarks
    context.model2 = SVC(kernel='rbf',
                         tol=1e-3,
                         random_state=0,
                         gamma=0.2,
                         C=10.0,
                         verbose=True)  # 8.05 for SVM model
    context.model3 = KNeighborsClassifier(
        n_neighbors=feature_num, p=3, metric='minkowski')  # 7.05 for  model
    context.model = DecisionTreeClassifier(criterion='entropy',
                                           max_depth=feature_num,
                                           random_state=0)
    context.model4 = RandomForestClassifier(criterion='entropy',
                                            n_estimators=feature_num,
                                            random_state=1,
                                            n_jobs=2)  # 5.2 for randomforest
    context.model1 = LogisticRegression(random_state=0,
                                        solver='lbfgs',
                                        multi_class='multinomial')
    context.modellist = {
        'SVM': context.model2,
        'KNeighbors': context.model3,
        'DecisionTree': context.model,
        'RandomForest': context.model4,
        'LogisticRegression': context.model1
    }
    context.lookback = 350  # Look back 62 days
    context.history_range = 350  # Only consider the past 400 days' history
    context.threshold = 4.05
    context.longprices = large_num
    context.shortprices = least_num
    set_long_only()
    # Generate a new model every week
    schedule_function(create_model, date_rules.week_end(),
                      time_rules.market_close(minutes=10))
    """
    # Generate a new model every week
    schedule_function(create_model1, date_rules.week_end(), time_rules.market_close(minutes=10))
    """

    # Trade at the start of every day
    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open(minutes=1))
Ejemplo n.º 15
0
def initialize(context):
    '''
        A function to define things to do at the start of the strategy
    '''
    # The context variables can be accessed by other methods
    context.params = {'lookback': 12, 'percentile': 0.05, 'min_volume': 1E7}

    # Call rebalance function on the first trading day of each month
    schedule_function(strategy, date_rules.month_start(),
                      time_rules.market_close(minutes=1))

    # Set up the pipe-lines for strategies
    attach_pipeline(make_strategy_pipeline(context), name='strategy_pipeline')
Ejemplo n.º 16
0
def initialize(context):
    __build_factor_basic_strategy(context)
    attach_pipeline(make_pipeline(context), 'my_pipeline')
    schedule_function(rebalance,
                      date_rules.week_end(days_offset=0),
                      half_days=True)
    # record my portfolio variables at the end of day
    schedule_function(func=recording_statements,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_close(),
                      half_days=True)
    print("initialize over")
    pass
Ejemplo n.º 17
0
def initialize(context):
    # Define Symbol
    context.security = symbol('MSFT')
    # Define standard devation threshold
    context.std_dev_threshold = 0.6

    schedule_function(enter_position,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open())

    schedule_function(square_off,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_close(minutes=1))
Ejemplo n.º 18
0
def initialize(context):
    context.security = sid(8554)  # Trade SPY
    context.model = RandomForestRegressor()

    context.lookback = 3  # Look back 3 days
    context.history_range = 400  # Only consider the past 400 days' history

    # Generate a new model every week
    schedule_function(create_model, date_rules.week_end(),
                      time_rules.market_close(minutes=10))

    # Trade at the start of every day
    schedule_function(trade, date_rules.every_day(),
                      time_rules.market_open(minutes=1))
Ejemplo n.º 19
0
def rebalance_scheduler(context):
    '''
        function to schedule a rebalancing trade. 
        The rebalancing is done based on the weights determined in the strategy core
        for each of the instruments defined in the trading universe.
    '''
    context.use_handle_data = False
    rebalance_freq = context.params.get('rebalance_freq',None)

    if rebalance_freq is None:
        return
    
    if context.params['verbose']:
        print('setting up {} scheduler'.format(rebalance_freq))
    
    if rebalance_freq == 'monthly':
        schedule_function(rebalance,
                    date_rules.month_start(days_offset=0),
                    time_rules.market_open(hours=5, minutes=30))
    elif rebalance_freq == 'weekly':
        schedule_function(rebalance,
                    date_rules.week_start(days_offset=0),
                    time_rules.market_open(hours=5, minutes=30))
    elif rebalance_freq == 'daily':
        schedule_function(rebalance,
                    date_rules.every_day(),
                    time_rules.market_open(hours=5, minutes=30))
    elif rebalance_freq.endswith('m'):
        try:
            context.trade_freq = int(rebalance_freq.split('m')[0])
            print('trade freq {}'.format(context.trade_freq))
            context.bar_count = 0
            context.use_handle_data = True
        except:
            raise ValueError('Invalid minute frequency')
    elif rebalance_freq.endswith('h'):
        try:
            context.trade_freq = int(rebalance_freq.split('h')[0])*60
            print('trade freq {}'.format(context.trade_freq))
            context.bar_count = 0
            context.use_handle_data = True
        except:
            raise ValueError('Invalid hourly frequency')
    else:
        raise ValueError('Un-recognized rebalancing frequency')

    if context.params['no_overnight_position']:
        schedule_function(square_off,
                    date_rules.every_day(),
                    time_rules.market_close(hours=3, minutes=30))
Ejemplo n.º 20
0
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())
Ejemplo n.º 21
0
def initialize(context):
    # This function runs once when sim starts.
    # Put your `schedule_function()`, `set_slippage`, and `set_commission` calls here.

    # FV is the five-year root symbol
    # TU is the ten-year root symbol
    context.asset_A = symbol('AAPL')
    context.asset_B = symbol('MSFT')

    # Keep state if we have crossed the ENTRY_THRESHOLD
    context.position_initiated = False

    # Run rebal function every day 15min before
    # close.
    schedule_function(func=rebal,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_close(minutes=15))
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)
Ejemplo n.º 23
0
def initialize(context):
    # Schedule our rebalance function to run at the start of
    # each week, when the market opens.
    # schedule_function(
    #     my_rebalance,
    #     date_rules.week_start(),
    #     time_rules.market_open()
    # )

    # Record variables at the end of each day.
    schedule_function(
        my_record_vars,
        date_rules.every_day(),
        time_rules.market_close()
    )

    # Create our pipeline and attach it to our algorithm.
    my_pipe = make_pipeline(20, 2)
    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.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):
    """
    Called once at the start of the algorithm.
    """
    context.n_longs = N_LONGS
    context.n_shorts = N_SHORTS
    context.min_positions = MIN_POSITIONS
    context.universe = assets

    set_slippage(slippage.FixedSlippage(spread=0.00))
    set_commission(commission.PerShare(cost=0, min_trade_cost=0))

    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open(hours=1, minutes=30))

    schedule_function(record_vars, date_rules.every_day(),
                      time_rules.market_close())

    pipeline = compute_signals()
    attach_pipeline(pipeline, 'signals')
Ejemplo n.º 26
0
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))
Ejemplo n.º 27
0
    def initialize(self, context):
        """
        initialize() is called once at the start of the program. Any one-time
        startup logic goes here.
        """

        # An assortment of securities from different sectors:
        # MSFT, UNH, CTAS, JNS, COG    sid(5061), 
        context.security_list = [symbol("MSFT"), symbol('UNH'), symbol('CTAS'), symbol('JNS'), symbol('COG')]
        #context.security_list = [sid(5061), sid(7792), sid(1941), sid(24556), sid(1746)]

        # Rebalance every Monday (or the first trading day if it's a holiday)
        # at market open.
        schedule_function(self.rebalance,
                          date_rules.week_start(days_offset=0),
                          time_rules.market_open())

        # Record variables at the end of each day.
        schedule_function(self.record_vars,
                          date_rules.every_day(),
                          time_rules.market_close())
Ejemplo n.º 28
0
def initialize(context):
    # Ethereum contract
    context.contract = ContractHandler()

    # Set Quandl API key and import fundamentals data from quandl
    quandl.ApiConfig.api_key = environ['QUANDL_API_KEY']
    context.fundamentals_earnings = quandl.get_table('SF0', qopts={'columns': ['ticker']}).\
        to_numpy()

    # Get blacklist of companies which returns a list of SIDs
    blacklist = context.contract.getBlacklist()
    set_do_not_order_list(blacklist)

    # Dictionary of stocks and their respective weights
    context.stock_weights = {}

    # Count of days before rebalancing
    context.days = 0

    # Number of sectors to go long in
    context.sect_numb = 2

    # Sector mappings
    context.sector_mappings = get_sectors()

    # Rebalance weekly on the first day of the week at market open
    schedule_function(rebalance,
                      date_rule=date_rules.week_start(),
                      time_rule=time_rules.market_open())

    schedule_function(record_positions,
                      date_rule=date_rules.week_start(),
                      time_rule=time_rules.market_close())

    # Register pipeline
    fundamental_df = make_pipeline(context)
    attach_pipeline(fundamental_df, 'fundamentals')
def initialize(context):
    # -----------------------------------------------------------------------------------------------
    c = context
    c.STOCKS = symbols('QQQ')
    c.BONDS = symbols('TLT', 'IEF')
    c.LEV = 1.00
    c.wt = {}
    c.A = symbol('SLV')
    c.B = symbol('GLD')
    c.C = symbol('XLI')
    c.D = symbol('XLU')
    c.MKT = symbol('QQQ')
    c.VOLA = 126
    c.LB = 1.00
    c.BULL = 1
    c.COUNT = 0
    c.OUT_DAY = 0
    c.RET_INITIAL = 80
    # -----------------------------------------------------------------------------------------------

    schedule_function(daily_check, date_rules.every_day(),
                      time_rules.market_open(minutes=140))
    schedule_function(record_vars, date_rules.every_day(),
                      time_rules.market_close())
def initialize (context) :
   
    # Algorithm parameters are defined here
    if ENVIRONMENT == 'RESEARCH':    
        context.benchmark = symbols('SPY')
        context.risk_free = symbols('SHY')
        context.cash_proxy = symbols('SHY')
    elif ENVIRONMENT == 'ZIPLINE' or ENVIRONMENT == 'IDE':
        context.benchmark = symbol('SPY')
        context.risk_free = symbol('SHY')
        context.cash_proxy = symbol('SHY')

    context.algo_transforms = [(['price'], ROCP, ['mom_63'], 62), 
                               (['price'], ROCP, ['mom_21'], 20), 
                               (['price'], average_historic_volatility, ['hvol_20'], 63, 20),
                               (['price'], SMA, ['short_mavg'], 21),
                               (['price'], SMA, ['long_mavg'], 63)
                               ]
    
    if ENVIRONMENT == 'ZIPLINE' or ENVIRONMENT == 'IDE':
        context.strategies = {
                                'strategy1': {
                                    'strat_wt' : 1.0,
                                    'strat_type' : 'SIGNAL',
                                    'alloc_type' : 'EQWT',   
                                    'portfolios' : [
                                                    symbols('VHT', 'VGT', 'VCR', 'IBB', 'EDV', 'VB', 'VAW', 
                                                            'TLT')
                                                    ],
                                    'weights' : [1.0],
                                    'n_top' : [1],
                                    'zscore_data' : ['+mom_63', '+mom_21', '-hvol_20'],
                                    'zscore_weights' : [0.7, 0.0, 0.3],
    #                                 'filter' : [lambda x,y: (x > y) & (x > 0), 'mom_21', ('mom_21', context.risk_free)]
    #                                 'filter' : []
                                    'filter' : [lambda x,y: x > y, 'mom_63', ('mom_63', context.risk_free)],
                                    'buy_trigger' : [lambda x,y: (x > y) and (context.buy_flag==False), 
                                                     'short_mavg', 'long_mavg'], 
                                    'sell_trigger' : [lambda x,y : (x < y) and (context.buy_flag==True), 
                                                      'short_mavg', 'long_mavg']
                                    }
                                }
        
    elif ENVIRONMENT == 'RESEARCH':
        context.strategies = {
                                'strategy1': {
                                    'strat_wt' : 1.0,
                                    'strat_type' : 'SIGNAL',
                                    'alloc_type' : 'EQWT',
                                    'portfolios' : [
                                                    [symbols('VHT'), symbols('VGT'), symbols('VCR'), 
                                                     symbols('IBB'), symbols('EDV'), symbols('VB'), 
                                                     symbols('VAW'), symbols('TLT')]
                                                    ],
                                    'weights' : [1.0],
                                    'n_top' : [1],
                                    'zscore_data' : ['+mom_63', '+mom_21', '-hvol_20'],
                                    'zscore_weights' : [0.7, 0.0, 0.3],
                                    # 'filter' : [lambda x,y: (x > y) & (x > 0), 'mom_21', 
                                    #             ('mom_21', context.risk_free)]
    #                                 'filter' : []
                                    'filter' : [lambda x,y: x > y, 'mom_63', ('mom_63', context.risk_free)], 
                                    'buy_trigger' : [lambda x,y: (x > y) and (context.buy_flag==False), 
                                                     'short_mavg', 'long_mavg'],
                                    'sell_trigger' : [lambda x,y : (x < y) and (context.buy_flag==True), 
                                                      'short_mavg', 'long_mavg']
                                    }
                                }

    # have to set this manually 'til I figure how to generate it programmatically from above parameters
    context.max_lookback = 120        # need additional data for recursive indicators like EMA, historic_vol etc.
    
    # set the appropriate time_rule offsets (hours, minutes) for order processing
    context.order_time_rule = time_rules.market_close(hours=0, minutes=1)
    
    context.threshold = 0.0     # only BUY/SELL if asset QTY changes by threshold%
    
    set_commission(commission.PerTrade(cost=0.0))  
    set_slippage(slippage.FixedSlippage(spread=0))
    
    #######################################################################################
    # THE FOLLOWING MUST ALWAYS BE INCLUDED AND MUST PRECEDE ANY SCHEDULED FUNCTIONS!
    # include this check to make sure that the algo parameters are formatted as required
    check_algo_parameters (context)
    # create a set of all the symbols used by the algorithm
    create_symbol_list(context)
    initialize_strat_variables(context)
    if ENVIRONMENT != 'IDE':
        add_strat_history(context)  
    #######################################################################################
    
    schedule_function(generate_strat_data,  
                     # date_rule=date_rules.month_start(days_offset=0),
                     date_rule=date_rules.month_start(days_offset=0),
                     time_rule=time_rules.market_open(hours=0, minutes=1),
                     half_days=True) 

#     schedule_function_by_interval(context, test_signal,  
#                      date_rule=date_rules.every_day(), 
#                      time_rule=time_rules.market_open(hours=0, minutes=5),
#                      half_days=True,
#                      freq=1)    
    
    # the 'freq' parameter is added to the norma schedule_function routine
    # to enable intervals of 'freq' periods - 1,2,3,.....  months
    schedule_function_by_interval(context, rebalance,  
                     date_rule=date_rules.month_start(days_offset=0), 
                     time_rule=time_rules.market_open(hours=0, minutes=5),
                     half_days=True,
                     freq=1)
    
    schedule_function_by_interval(context, handle_orders,  
                     date_rule=date_rules.month_start(days_offset=0), 
                     time_rule=time_rules.market_close(hours=0, minutes=15),
                     half_days=True,
                     freq=1)
Ejemplo n.º 31
0
def initialize(context):
    # these must ALWAYS be present!
    context.transforms = []
    context.algo_rules = []
    context.max_lookback = 63
    context.outstanding = {}  # orders which span multiple days

    context.raw_data = {}

    #############################################################
    # set the following parameters as required

    context.show_positions = True
    # select records to show in algo.show_records()
    context.show_records = True

    # replace cash_proxy with risk_free if cantec.allow_cash_proxY_replacement is True
    # and cash_proxy price is <= average cash_proxy price over last context.cash_proxy_lookback days
    context.allow_cash_proxy_replacement = False
    context.cash_proxy_lookback = 43  # must be <= context.max_lookback

    context.update_metrics = False
    # to calculate Sharpe ratio
    context.calculate_SR = False
    context.SR_lookback = 63  # must be <= context.max_lookback
    context.SD_factor = 0

    # position only changed if percentage change > threshold
    context.threshold = 0.01

    # the following can be changed
    context.market_proxy = symbols('VFINX')[0]
    context.risk_free = symbols('VFISX')[0]
    # context.market_proxy = symbols('SPY')[0]
    # context.risk_free = symbols('SHY')[0]

    set_commission(commission.PerTrade(cost=10.0))
    context.leverage = 1.0
    #################################################################
    # configure strategies

    context.rebalance_interval = 3  # set interval to n = no of periods (default: months)
    # if you want to change default period, change schedule reallocate below

    # Strategy 1

    rs0003 = StrategyParameters(
        context,
        name='rs0003',
        portfolios=[symbols('NHMAX', 'FAGIX', 'VFIIX')],
        # portfolios=[symbols('HYD','HYD','MBB')],
        portfolio_allocation_modes=['EW'],
        portfolio_allocation_kwargs=[{}],
        security_weights=[None],
        portfolio_allocation_formulas=[None],
        scoring_methods=['RS'],
        scoring_factors=[{
            '+momentum': 1.0
        }],
        n_tops=[1],
        protection_modes=['BY_RULE'],
        protection_rules=['smma_rule'],
        protection_formulas=[None],
        cash_proxies=[symbol('VFISX')],
        # cash_proxies=[symbol('SHY')],
        strategy_allocation_mode='FIXED',
        portfolio_weights=[1.0],
        strategy_allocation_formula=None,
        strategy_allocation_rule=None)

    Configurator(context, define_transforms, define_rules, strategies=[rs0003])

    ############################
    # configure algorithm

    algo = Algo(context,
                strategies=[rs0003.strategy],
                allocation_model=AllocationModel(context,
                                                 mode='EW',
                                                 weights=None,
                                                 formula=None),
                regime=None)
    ###########################################################################################################
    # generate algo data every day at close
    schedule_function(algo.update_data, date_rules.every_day(),
                      time_rules.market_close())

    # daily functions to handle GTC orders
    schedule_function(algo.check_for_unfilled_orders, date_rules.every_day(),
                      time_rules.market_close())
    schedule_function(algo.fill_outstanding_orders, date_rules.every_day(),
                      time_rules.market_open())

    if context.update_metrics:
        # calculate metrics every day
        schedule_function(algo.update_metrics, date_rules.every_day(),
                          time_rules.market_close())

    if context.show_positions:
        schedule_function(algo.show_positions,
                          date_rules.month_start(days_offset=0),
                          time_rules.market_open())

    if context.show_records:
        # show records every day
        # edit the show_records function to include records required
        schedule_function(algo.show_records, date_rules.every_day(),
                          time_rules.market_close())

    schedule_function(algo.rebalance, date_rules.month_end(days_offset=2),
                      time_rules.market_open())