示例#1
0
文件: test_algos.py 项目: xyicheng/bt
def test_select_all():
    algo = algos.SelectAll()

    s = bt.Strategy('s')

    dts = pd.date_range('2010-01-01', periods=3)
    data = pd.DataFrame(index=dts, columns=['c1', 'c2'], data=100.)
    data['c1'][dts[1]] = np.nan
    data['c2'][dts[1]] = 95

    s.setup(data)
    s.update(dts[0])

    assert algo(s)
    selected = s.temp['selected']
    assert len(selected) == 2
    assert 'c1' in selected
    assert 'c2' in selected

    # make sure don't keep nan
    s.update(dts[1])

    assert algo(s)
    selected = s.temp['selected']
    assert len(selected) == 1
    assert 'c2' in selected

    # if specify include_no_data then 2
    algo = algos.SelectAll(include_no_data=True)

    assert algo(s)
    selected = s.temp['selected']
    assert len(selected) == 2
    assert 'c1' in selected
    assert 'c2' in selected
示例#2
0
    def bt_strategy(self, data, cats, graph_path):

        rsmpl = {
            'days': 'B',
            'weeks': 'W-Fri',
            'months': 'BM',
            'years': 'BY'
        }[self.roll_ptype]

        first_date = data.index[0] + relativedelta(**{self.est_ptype: self.est_plen})
        run_dates = asfreq_actual(data[data.columns[0]], str(self.roll_plen) + rsmpl)
        run_dates = data.loc[run_dates.index]
        run_dates = run_dates.loc[run_dates.index > first_date]
        run_dates = run_dates.iloc[:-1]
        run_dates.loc[data.index[-1]] = data.iloc[-1]

        fee_func_parial = partial(fee_func, ff=self.fix_fee, pf=self.prc_fee)

        algo_stack = [
            algos.RunOnDate(*run_dates.index.tolist()),
            algos.SelectAll(),
            SaveWeights(),
            WeightHRP(plen=self.est_plen, ptype=self.est_ptype, robust=self.robust, ddev=self.ddev, cats=cats, graph_path=graph_path),
            GapWeights(self.reb_gap),
        ]

        if self.is_tvol:
            algo_stack.append(WeightTargetVol(self.tvol, plen=self.est_plen, ptype=self.est_ptype, kmax=self.leverage))

        algo_stack.extend([
            WeightAdjust(self.leverage, self.weight_round),
            LimitWeights(self.min_weight, self.max_weight, self.leverage),
            WeightsToPerm(),
            CheckFeeBankrupt(fee_func_parial),
            algos.Rebalance()
        ])

        strategy = bt.Strategy(self.name(), algo_stack)

        return bt.Backtest(strategy, data.copy(), initial_capital=self.init_balance,
                           commissions=fee_func_parial, integer_positions=self.int_pos, progress_bar=True)