Beispiel #1
0
def initialize(context):
    ''' Initialize global vars'''
    context.long_leverage = 0.1
    context.short_leverage = -0.9
    context.returns_lookback = 16
    context.pct_per_stock = 0.5
    
    context.fastperiod = 12
    context.slowperiod = 26
    context.signalperiod = 9
    context.bar_count = 90

    set_commission(commission.PerShare(cost=0.0014, min_trade_cost=1))
    
    # Rebalance on the first trading day of each week at 12AM.
    schedule_function(rebalance, date_rules.week_start(days_offset=0),time_rules.market_open(hours=0.5))
    
    # Rebalance mid-week
    schedule_function(cut_losses, date_rules.week_start(days_offset=2),time_rules.market_open(hours=0.5))

    # Record tracking variables at the end of each day.
    schedule_function(record, date_rules.every_day(),time_rules.market_open(minutes=1))


    # Create and attach our pipeline (dynamic stock selector), defined below.
    attach_pipeline(make_pipeline(context),
                    'mean_reversion_macd_learning')
Beispiel #2
0
def initialize(context):
    model = g_models[g_idx]
    print("hello world --- :",g_idx,model)
    attach_pipeline(make_pipeline(asset_finder=None,algo_mode=model), 'my_pipeline')
    schedule_function(rebalance, date_rules.week_start(days_offset=0), half_days=True)
    context.posset = {}
    context.rbcnt = 0
def initialize(context):
    """Setup: register pipeline, schedule rebalancing,
        and set trading params"""
    attach_pipeline(compute_factors(), 'factor_pipeline')
    schedule_function(rebalance,
                      date_rules.week_start(),
                      time_rules.market_open(),
                      calendar=calendars.US_EQUITIES)

    set_commission(us_equities=commission.PerShare(cost=0.00075, min_trade_cost=.01))
    set_slippage(us_equities=slippage.VolumeShareSlippage(volume_limit=0.0025, price_impact=0.01))
Beispiel #4
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))
Beispiel #5
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):
    '''
        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())
Beispiel #7
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())
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))
Beispiel #9
0
def initialise(context):
    schedule_function(strategy ,date_rules.week_start(),
                     time_rules.market_open(minutes = 15))