コード例 #1
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())
コード例 #2
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())
コード例 #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()
        )
コード例 #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
コード例 #5
0
def initialize(context):
    context.fut = continuous_future('ES', roll='calendar')

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

    context.i = 0
    context.invested = False
コード例 #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.record_rank = {}
    context.save2mysql = 0
    # 模型训练参数
    context.horizon = 6
    context.percent = 5
    context.model_name = 'adaBoost'
    context.rolling = 1  # 是否为滚动,0为不滚动
    context.ishistory = 0  #是否用历史分类。0为不使用
    context.train_period = 12 * 1
    context.i = 0
    set_slippage(slippage.FixedSlippage(spread=0.00))
    set_commission(commission.PerDollar(cost=0.00325))

    month = 21
    week = 5
    rf = 0.025
    c = 252

    if context.namespace["fund_type"] == 'stock':
        benchmark = '000300.SH'
        fund_type = 1
    elif context.namespace["fund_type"] == 'hybrid':
        benchmark = '000300.SH'
        fund_type = 2
    elif context.namespace["fund_type"] == 'bond':
        benchmark = '037.CS'
        fund_type = 3
    # 选择基金池和benchmark
    ben_sid = symbol(benchmark).sid
    df_stock = df.query("update_time == update_time.max() and type_code=={"\
                        "type}".format(type = fund_type))
    # 基金900 开头的不需要,专门去掉
    df_stock = df_stock[df_stock["fund_code"] < '900000'].fund_code + ".OF"
    sfilt = SpecificAssets(symbols(
        benchmark, *tuple(df_stock)))  # 使用到的数据,包括基金和对应benchmark指数
    sample_filt = SpecificAssets(symbols(
        *tuple(df_stock)))  # 只包含基金,因为评级不应该包含benchmark,故在事后screen去掉benchmark

    # 只包含基金,因为评级不应该包含benchmark,故在事后screen去掉benchmark
    ## 16个因子指标
    down_sharpe = Down_sharpe(window_length=9 * month, rf=rf, c=c, mask=sfilt)
    drawdown = Drawdown(window_length=9 * month, mask=sfilt)
    dvar = Down_variation(window_length=9 * month, rf=rf, c=c, mask=sfilt)
    mean_r = Average_return(window_length=9 * month, mask=sfilt)
    lasting = Lasting(window_length=9 * month,
                      mask=sfilt,
                      time=6 * month,
                      percent=20)
    emr = Emr(window_length=9 * month, mask=sfilt, time=6 * month)
    rlt_var = Negative_variation(window_length=9 * month, c=c, mask=sfilt)
    mcv_in = Mcv_in(window_length=9 * month,
                    rf=rf,
                    c=c,
                    mask=sfilt,
                    time=week,
                    index_sid=ben_sid)
    rank_stable = Rank_stable(window_length=9 * month,
                              mask=sfilt,
                              time=6 * month)
    select_time, select_stock = CL(window_length=9 * month,
                                   rf=rf,
                                   mask=sfilt,
                                   time=week,
                                   index_sid=ben_sid)
    hit_rate = Hit_rate(window_length=10 * month,
                        mask=sfilt,
                        time=6 * month,
                        time_window=9 * month,
                        index_sid=ben_sid)
    value_at_risk = Value_at_risk(window_length=9 * month,
                                  mask=sfilt,
                                  q_value=5,
                                  time=6 * month)
    beta_in = Beta_in(window_length=9 * month,
                      mask=sfilt,
                      rf=rf,
                      time=week,
                      index_sid=ben_sid)
    bias_in = Bias_in(window_length=9 * month, mask=sfilt, time=126)
    ir = Information_ratio(window_length=9 * month,
                           mask=sfilt,
                           time=1,
                           index_sid=ben_sid)
    # 预测因变量Y
    _ry = Lag_Return(window_length=context.horizon * month, mask=sfilt)
    _sp = Lag_Sharpe(window_length=context.horizon * month, mask=sfilt)

    pipe = Pipeline(columns={
        "dhsp": down_sharpe,
        "drwd": drawdown,
        "dvar": dvar,
        "mean_r": mean_r,
        "lasting": lasting,
        "emr": emr,
        "rlt_var": rlt_var,
        "mcv_in": mcv_in,
        "rank_stable": rank_stable,
        "select_time": select_time,
        "select_stock": select_stock,
        "hit_rate": hit_rate,
        "value_at_risk": value_at_risk,
        "beta_in": beta_in,
        "bias_in": bias_in,
        "ir": ir,
        "_ry": _sp
    },
                    screen=sample_filt)

    attach_pipeline(pipe, 'my_pipeline')
    set_max_leverage(1.1)
    schedule_function(rebalance,
                      date_rule=date_rules.month_start(),
                      time_rule=time_rules.market_open())

    # 初始化记录变量
    context.rank_score = pd.Series()
    context.f = pd.Panel()
    context.f_dict = {}
    context.reb_flag = False
    context.B = {}
コード例 #11
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))
コード例 #12
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