def initialize(context):
    schedule_function(func=trade,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open(),
                      half_days=True)
    schedule_function(func=cancel,
                      time_rule=time_rules.market_close(minutes=5),
                      date_rule=date_rules.every_day(),
                      half_days=True)
    schedule_function(func=reorder,
                      time_rule=time_rules.market_open(minutes=5),
                      date_rule=date_rules.every_day(),
                      half_days=True)
    context.asserts = symbols('SPY')
    context.bonds = symbol('SHY')
    context.rebalance_date = 0
    context.fired = False
    context.rebalance_inteval = 'D'  #'Q', #'D', #'M' #'Q' #'Y'
    context.top_n_by_momentum = pd.Series()
    #Choose X stocks out of portfolio of Y stocks- how many stocks to hold - top X by momentum
    context.stocks = 1
    #Lookback for momentum calculation
    context.momentum_days = 60
    #set at less than 1 to ensure no leverage
    context.leverage_buffer = 0.99
    #Set to 0 to reject any stocks with negative momentum, set to -1 to accept stocks with negative momentum
    context.trend = 0.0
    context.reorder_dict = {}
    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')
Beispiel #3
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()
        )
Beispiel #4
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
Beispiel #5
0
def initialize(context):

    # Get continuous futures for Light Sweet Crude Oil...
    context.crude_oil = continuous_future('CL', roll='calendar')
    # ... and RBOB Gasoline
    context.gasoline = continuous_future('RB', roll='calendar')

    # If Zipline has trouble pulling the default benchmark, try setting the
    # benchmark to something already in your bundle
    set_benchmark(context.crude_oil)

    # Ignore commissions and slippage for now
    set_commission(us_futures=commission.PerTrade(cost=0))
    set_slippage(us_futures=slippage.FixedSlippage(spread=0.0))

    # Long and short moving average window lengths
    context.long_ma = 65
    context.short_ma = 5

    # True if we currently hold a long position on the spread
    context.currently_long_the_spread = False
    # True if we currently hold a short position on the spread
    context.currently_short_the_spread = False

    # Rebalance pairs every day, 30 minutes after market open
    schedule_function(func=rebalance_pairs,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open(minutes=30))

    # Record Crude Oil and Gasoline Futures prices everyday
    schedule_function(record_price, date_rules.every_day(),
                      time_rules.market_open())
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))
Beispiel #7
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))
Beispiel #8
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))
Beispiel #9
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))
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())
Beispiel #11
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))
Beispiel #12
0
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):
    attach_pipeline(make_pipeline(), 'pipeline')
    #Schedule Functions
    if not IS_LIVE:
        schedule_function(
            trade,
            #date_rules.every_day(),
            #date_rules.week_end(days_offset=1),#0=Fri 1= Thurs
            date_rules.month_end(days_offset=3),
            time_rules.market_close(minutes=30)
        )
        schedule_function(record_vars, date_rules.every_day(), time_rules.market_close())
        schedule_function(cancel_open_orders, date_rules.week_end(days_offset=2), time_rules.market_close())
    
    context.spy = symbol('SPY')  #sid(8554) #SPY
    context.TF_filter = False
    #context.TF_lookback = 60
    #Set number of securities to buy and bonds fund (when we are out of stocks)
    context.Target_securities_to_buy = 15 #10 #15 #2 #1 #5 #10 #5
    
    context.bonds = symbol('IEF') #sid(23870)  #IEF
    context.relative_momentum_lookback = 44 #66 #22 #4 #22 #22 #22 #126 #Momentum lookback
    context.momentum_skip_days = 1
    context.top_n_relative_momentum_to_buy = 10 #15 #10 #15 #1 #5 #5 #10 #5 #Number to buy
    context.stock_weights = pd.Series()
    context.bond_weights = pd.Series()

    context.auto_close = {} #Initialize portfolio auto_close list.
    context.TRACK_ORDERS_ON = False
Beispiel #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 = 6
    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
    context.time_series = 0
    context.init = 0
    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))
Beispiel #15
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 #16
0
def initialize(context):
    # Benchmark against the Dow Jones Industrial Average (DIA)
    set_benchmark(symbol('DIA'))

    # stop when trying to handle missing data
    set_nodata_policy(NoDataPolicy.EXCEPTION)

    # These are the default commission and slippage settings.  Change them to fit your
    # brokerage fees. These settings only matter for backtesting.  When you trade this
    # algorithm, they are moot - the brokerage and real market takes over.
    set_commission(commission.PerTrade(cost=0.03))
    set_slippage(slippage.VolumeShareSlippage(volume_limit=0.25, price_impact=0.1))

    # create an instance of the Dow30 class and set it within context
    context.dow30 = Dow30()

    # next trade year
    context.year = 0

    # set to True to trigger a rebalance
    context.trade = False

    # for tracking max leverage
    context.mx_lvrg = 0

    # check for possible trade, daily
    schedule_function(func=rebalance, date_rule=date_rules.every_day(), time_rule=time_rules.market_open(hours=1))
Beispiel #17
0
def initialize(context):
    attach_pipeline(make_pipeline(), 'my_pipeline')

    # Rebalance each day.  In daily mode, this is equivalent to putting
    # `rebalance` in our handle_data, but in minute mode, it's equivalent to
    # running at the start of the day each day.
    schedule_function(rebalance, date_rules.every_day())
Beispiel #18
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))
Beispiel #19
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())
Beispiel #20
0
def initialize(context):

    # Schedule our rebalance function to run at the start of
    # each week, when the market opens.
    schedule_function(func=my_rebalance,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open())
Beispiel #21
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))
def initialize(context):

    __build_deeplearn_strategy(context)
    attach_pipeline(make_pipeline(context), 'my_pipeline')
    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.every_minute())
    # record my portfolio variables at the end of day
    print("initialize over")
    pass
Beispiel #23
0
def initialize(context):
    context.params = {'lookback':12, 'min_volume':1E7
                      }
    
    schedule_function(strategy, date_rules.every_day(), 
            time_rules.market_open(minutes=30))

    attach_pipeline(make_strategy_pipeline(context), 
            name='strategy_pipeline')
def initialize(context):
    schedule_function(func=trade,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open(),
                      half_days=True)
    context.asserts = symbols('SPY', 'SHY', 'TLT', 'GLD')
    context.asserts_position = [0.25, 0.25, 0.25, 0.25]
    context.rebalance_inteval = 'Q'  #'Q', #'D', #'M' #'Q' #'Y'
    context.rebalance_date = 0
    context.fired = False
Beispiel #25
0
def initialize(context):

    context.security = symbol(SYMBOL)  # Trade
    set_benchmark(symbol(SYMBOL))  # Set benchmarks
    #print(context.security)
    context.start = True
    set_long_only()
    schedule_function(market_open, date_rules.every_day(),
                      time_rules.market_open(minutes=1))
    context.orders_submitted = False
Beispiel #26
0
def initialize(context):
    attach_pipeline(make_pipeline(), 'my_pipeline')

    # Explicitly set the commission/slippage to the "old" value until we can
    # rebuild example data.
    # github.com/quantopian/zipline/blob/master/tests/resources/
    # rebuild_example_data#L105
    context.set_commission(commission.PerShare(cost=.0075, min_trade_cost=1.0))
    context.set_slippage(VolumeShareSlippage())

    schedule_function(rebalance2, date_rules.every_day())
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')
Beispiel #28
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))
Beispiel #29
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
Beispiel #30
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
Beispiel #31
0
def initialize(context):
    attach_pipeline(make_pipeline(), 'my_pipeline')

    # Rebalance each day.  In daily mode, this is equivalent to putting
    # `rebalance` in our handle_data, but in minute mode, it's equivalent to
    # running at the start of the day each day.
    schedule_function(rebalance, date_rules.every_day())

    # Explicitly set the commission to the "old" value until we can
    # rebuild example data.
    # github.com/quantopian/zipline/blob/master/tests/resources/
    # rebuild_example_data#L105
    context.set_commission(commission.PerShare(cost=.0075, min_trade_cost=1.0))
Beispiel #32
0
def initialize(context):
    attach_pipeline(make_pipeline(), 'my_pipeline')

    # Rebalance each day.  In daily mode, this is equivalent to putting
    # `rebalance` in our handle_data, but in minute mode, it's equivalent to
    # running at the start of the day each day.
    schedule_function(rebalance, date_rules.every_day())

    # Explicitly set the commission to the "old" value until we can
    # rebuild example data.
    # github.com/quantopian/zipline/blob/master/tests/resources/
    # rebuild_example_data#L105
    context.set_commission(commission.PerShare(cost=.0075, min_trade_cost=1.0))