コード例 #1
0
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())
コード例 #2
0
def initialize(context):

    # Let's set a look up date inside our backtest to ensure we grab the correct security
    #set_symbol_lookup_date('2015-01-01')

    # Use a very liquid set of stocks for quick order fills
    context.symbol = symbol('SPY')
    #context.stocks = symbols(['TWX','AIG','PSX','EMC','YHOO','MDY','TNA','CHK','FXI',
    #                            'PEP','SBUX','VZ','VWO','TWC','HAL','MDLZ','CAT','TSLA',
    #                            'MU','PM','WYNN','MET',NOV BRK_B SNDK ESRX YELP])
    #set_universe(universe.DollarVolumeUniverse(99.5, 100))
    #set_benchmark(symbol('SPY'))

    # set a more realistic commission for IB, remove both this and slippage when live trading in IB
    set_commission(commission.PerShare(cost=0.014, min_trade_cost=1.4))

    # Default slippage values, but here to mess with for fun.
    set_slippage(
        slippage.VolumeShareSlippage(volume_limit=0.25, price_impact=0.1))

    # Use dicts to store items for plotting or comparison
    context.next_pred_price = {}  # Current cycles prediction

    #Change us!
    context.history_len = 500  # How many days in price history for training set
    context.out_of_sameple_bin_size = 2
    context.score_filter = -1000.0
    context.action_to_move_percent = 0.0

    # Register 2 histories that track daily prices,
    # one with a 100 window and one with a 300 day window
    add_history(context.history_len, '1d', 'price')
    context.i = 0
コード例 #3
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
コード例 #4
0
    def initialize(context):
        """Set initialization params for a backtest"""
        # trading pair
        context.asset = symbol(trading_pair)
        # trading signals, dict, timestamp:amount
        context.trades = trades

        # transaction cost
        if commission_is_per_share:
            context.set_commission(
                commission.PerShare(cost=commission_cost, min_trade_cost=0))
        else:
            context.set_commission(commission.PerTrade(cost=commission_cost))
コード例 #5
0
    def initialize_commission(self, country='US', platform='IB'):
        """Sets commissions

        See https://www.quantopian.com/help#ide-commission and
            https://www.quantopian.com/docs/api-reference/algorithm-api-reference#zipline.finance.commission.PerDollar
        """
        if (country == 'SG'):
            set_commission(SGCommission(platform=platform))
        else:
            # IB broker for US is the top stock broker in US
            # https://brokerchooser.com/best-brokers/best-stock-brokers-in-the-us
            # Typical commission is USD 0.005 per share, minimum per order USD 1.00
            # https://www1.interactivebrokers.com/en/index.php?f=1590&p=stocks
            set_commission(commission.PerShare(cost=0.005, min_trade_cost=1))
コード例 #6
0
ファイル: futures_algo.py プロジェクト: yanding/misc_research
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())
コード例 #7
0
    def initialize(self, context):
        add_history(200, '1d', 'price')
        set_slippage(slippage.FixedSlippage(spread=0.0))
        set_commission(commission.PerShare(cost=0.01, min_trade_cost=1.0))
        context.tick = 0

        dp_data = self.data
        df_data = pd.DataFrame(index=dp_data.axes[1])
        df_data['close'] = dp_data[:, :, 'close']
        df_data['open'] = dp_data[:, :, 'open']
        df_data['high'] = dp_data[:, :, 'high']
        df_data['low'] = dp_data[:, :, 'low']
        df_data['volume'] = dp_data[:, :, 'volume']

        self.atr = atr_per_close(df_data, atrLen = self.atr_len)
        context.longstop = 0
コード例 #8
0
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')
コード例 #9
0
def initialize(context):
    '''
    Called once at the very beginning of a backtest (and live trading). 
    Use this method to set up any bookkeeping variables.
    
    The context object is passed to all the other methods in your algorithm.

    Parameters

    context: An initialized and empty Python dictionary that has been 
             augmented so that properties can be accessed using dot 
             notation as well as the traditional bracket notation.
    
    Returns None
    '''
    # 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))
    context.tick = 0
コード例 #10
0
def initialize(context):
    context.i = 0
    context.sym = symbol('LKTB')
    context.hold = False
    set_commission(commission.PerShare(cost=0.000008))
    set_slippage(slippage.FixedSlippage(spread=0))
コード例 #11
0
ファイル: AAA.py プロジェクト: zfy1989lee/Trading_Strategies
 def initialize(self, context):
     add_history(60, '1d', 'price')
     set_slippage(slippage.FixedSlippage(spread=0.0))
     set_commission(commission.PerShare(cost=0.01, min_trade_cost=1.0))
     context.tick = 0