Exemplo n.º 1
0
def test_example():
    data = pd.DataFrame({
        'code': ['000001' for x in range(4)],
        'date':
        [dt(1998, 1, 1),
         dt(1999, 1, 1),
         dt(2000, 1, 1),
         dt(2001, 1, 1)],
        'close': [4.5, 7.9, 6.7, 10],
    })
    bt = BackTest(data,
                  init_cash=1000,
                  callbacks=[
                      MinAmountChecker(buy_dict={
                          '000001': [dt(1998, 1, 1),
                                     dt(2000, 1, 1)]
                      },
                                       sell_dict={'000001': [dt(1999, 1, 1)]})
                  ])
    bt.calc_trade_history()
    print(bt.report())
    assert 100 == bt.hold_price_cur_df.loc['000001']['amount']
    assert np.round(6.7, 2) == np.round(
        bt.hold_price_cur_df.loc['000001']['buy_price'], 2)
    assert np.round(bt.total_assets_cur,
                    2) == np.round(bt.available_cash + 10 * 100, 2)
    assert bt._BackTest__get_buy_avg_price('000001') == (6.7, 100.0)
Exemplo n.º 2
0
def test_backtest_holdprice(init_global_data):
    data = pd.DataFrame({
        'code': ['000001' for x in range(5)],
        'date': [
            dt(1998, 1, 1),
            dt(1999, 1, 1),
            dt(2000, 1, 1),
            dt(2001, 1, 1),
            dt(2002, 1, 1)
        ],
        'close': [4.5, 7.9, 6.7, 13.4, 15.3],
    })
    data = data.append(
        pd.DataFrame({
            'code': ['000002' for x in range(5)],
            'date': [
                dt(1998, 12, 31),
                dt(1999, 12, 31),
                dt(2000, 12, 31),
                dt(2001, 12, 31),
                dt(2002, 12, 31)
            ],
            'close': [41.5, 71.9, 61.7, 131.4, 151.3],
        }))
    bt = BackTest(
        data,
        init_cash=100000,
        callbacks=[
            MinAmountChecker(buy_dict={
                '000001': [dt(1999, 1, 1), dt(2001, 1, 1)],
                '000002':
                [dt(1999, 12, 31),
                 dt(2000, 12, 31),
                 dt(2002, 12, 31)]
            },
                             sell_dict={})
        ])
    bt.calc_trade_history()
    print(bt.report())
    assert bt._BackTest__get_buy_avg_price('000001') == np.average(
        [7.9, 13.4], weights=[100, 100], returned=True)
    assert bt._BackTest__get_buy_avg_price('000002') == np.average(
        [71.9, 61.7, 151.3], weights=[100, 100, 100], returned=True)
    assert 200 == bt.hold_price_cur_df.loc['000001']['amount']
    assert np.round(
        (7.9 + 13.4) / 2,
        2) == np.round(bt.hold_price_cur_df.loc['000001']['buy_price'], 2)
    assert 300 == bt.hold_price_cur_df.loc['000002']['amount']
    assert np.round(
        (71.9 + 61.7 + 151.3) / 3,
        2) == np.round(bt.hold_price_cur_df.loc['000002']['buy_price'], 2)
    assert bt.total_assets_cur == bt.available_cash + (15.3 * 200) + (151.3 *
                                                                      300)
Exemplo n.º 3
0
def test_backtest_calc(init_global_data):
    bt = BackTest(pytest.global_data,
                  callbacks=[
                      MinAmountChecker(
                          buy_dict={
                              pytest.global_code:
                              [dt(1999, 1, 1), dt(2001, 1, 1)]
                          },
                          sell_dict={
                              pytest.global_code:
                              [dt(2000, 1, 1), dt(2002, 1, 1)]
                          },
                      )
                  ])
    bt.calc_trade_history()
    assert not bt.history_df.empty
    assert bt._BackTest__get_buy_avg_price('000001') == (0.0, 0.0)
    print(bt.report())
    assert bt.available_hold_df.empty
    bt = BackTest(pytest.global_data,
                  callbacks=[
                      MinAmountChecker(
                          buy_dict={
                              pytest.global_code:
                              [dt(1999, 1, 1), dt(2001, 1, 1)]
                          },
                          sell_dict={pytest.global_code: [dt(2000, 1, 1)]},
                      )
                  ])
    bt.calc_trade_history()
    assert not bt.history_df.empty
    print(bt.report())
    print(bt.hold_time())
    print(bt.hold_price_cur_df)
    assert not bt.available_hold_df.empty
    assert bt.available_hold_df[pytest.global_code] == 100
    assert bt._BackTest__get_buy_avg_price('000001') == (13.4, 100.0)
Exemplo n.º 4
0
def test_backtest_calc_sameday(init_global_data):
    bt = BackTest(pytest.global_data,
                  callbacks=[
                      MinAmountChecker(
                          colname=None,
                          buy_dict={
                              pytest.global_code:
                              [dt(1999, 1, 1), dt(2001, 1, 1)]
                          },
                          sell_dict={
                              pytest.global_code:
                              [dt(2001, 1, 1), dt(2002, 1, 1)]
                          },
                      )
                  ])
    bt.calc_trade_history(verbose=2)
    assert bt.available_hold_df.empty
    assert 2 == len(bt.history_df)
Exemplo n.º 5
0
def test_init_hold():
    data = pd.DataFrame({
        'code': ['000001' for x in range(4)],
        'date':
        [dt(1998, 1, 1),
         dt(1999, 1, 1),
         dt(2000, 1, 1),
         dt(2001, 1, 1)],
        'close': [4.5, 7.9, 6.7, 10],
    })
    init_hold = pd.DataFrame({
        'code': ['000001'],
        'amount': [400],
        'price': [3],
        'buy_date': [dt(1998, 1, 1)],
        'stoploss_price': [-1],
        'stopprofit_price': [-1],
        'next_price': [-1],
    })
    bt = BackTest(data, init_hold=init_hold)
    assert not bt.available_hold_df.empty
    assert bt.available_hold_df['000001'] == 400
    assert bt.hold_price_cur_df.loc['000001', 'buy_price'] == 3.0
    assert bt.hold_price_cur_df.loc['000001', 'amount'] == 400
    assert bt.hold_price_cur_df.loc['000001', 'price_cur'] == 10.0
    bt.calc_trade_history()
    print(bt.report())

    bt = BackTest(
        data,
        init_hold=init_hold,
        callbacks=[
            MinAmountChecker(
                sell_dict={'000001': [dt(1999, 1, 1),
                                      dt(2000, 1, 1)]})
        ])
    bt.calc_trade_history()
    assert not bt.history_df.empty
    assert bt.available_hold_df['000001'] == 200
    assert bt.available_cash > bt.init_cash
    assert bt.total_assets_cur == bt.available_cash + 200 * 10  #最新价格10元,总共持有200股
    print(bt.report())
Exemplo n.º 6
0
def test_example_backtest_date(init_global_data):
    print(
        ">>> from datetime import date as dt\n"
        ">>> data = pd.DataFrame({\n"
        ">>>     'code': ['000001' for x in range(5)],\n"
        ">>>     'date': [\n"
        ">>>         dt(1998, 1, 1),\n"
        ">>>         dt(1999, 1, 1),\n"
        ">>>         dt(2000, 1, 1),\n"
        ">>>         dt(2001, 1, 1),\n"
        ">>>         dt(2002, 1, 1)\n"
        ">>>     ],\n"
        ">>>     'close': [4.5, 7.9, 6.7, 13.4, 15.3]\n"
        ">>> })\n"
        ">>> data['date'] = pd.to_datetime(data['date'])\n"
        ">>> bt = BackTest(\n"
        ">>>     data,\n"
        ">>>     callbacks=[\n"
        ">>>         MinAmountChecker(\n"
        ">>>             buy_dict={\n"
        ">>>                 pytest.global_code:\n"
        ">>>                 data[data['date'] < '2000-1-1']['date'].dt.to_pydatetime()\n"
        ">>>             },\n"
        ">>>             sell_dict={\n"
        ">>>                 pytest.global_code:\n"
        ">>>                 data[data['date'] > '2000-1-1']['date'].dt.to_pydatetime()\n"
        ">>>             },\n"
        ">>>         )\n"
        ">>>     ])\n"
        ">>> bt.calc_trade_history()\n"
        ">>> bt.report())\n")

    data = pd.DataFrame({
        'code': ['000001' for x in range(5)],
        'date': [
            dt(1998, 1, 1),
            dt(1999, 1, 1),
            dt(2000, 1, 1),
            dt(2001, 1, 1),
            dt(2002, 1, 1)
        ],
        'close': [4.5, 7.9, 6.7, 13.4, 15.3]
    })
    data['date'] = pd.to_datetime(data['date'])
    bt = BackTest(
        data,
        callbacks=[
            MinAmountChecker(
                buy_dict={
                    pytest.global_code:
                    data[data['date'] < '2000-1-1']['date'].dt.to_pydatetime()
                },
                sell_dict={
                    pytest.global_code:
                    data[data['date'] > '2000-1-1']['date'].dt.to_pydatetime()
                },
            )
        ])
    bt.calc_trade_history()
    assert not bt.history_df.empty
    print(bt.report())
Exemplo n.º 7
0
def test_backtest_calc_mutil(init_global_data):
    data = pd.DataFrame({
        'code': ['000001' for x in range(5)],
        'date': [
            dt(1998, 1, 1),
            dt(1999, 1, 1),
            dt(2000, 1, 1),
            dt(2001, 1, 1),
            dt(2002, 1, 1)
        ],
        'close': [4.5, 7.9, 6.7, 13.4, 15.3],
    })
    data = data.append(
        pd.DataFrame({
            'code': ['000002' for x in range(5)],
            'date': [
                dt(1998, 12, 31),
                dt(1999, 12, 31),
                dt(2000, 12, 31),
                dt(2001, 12, 31),
                dt(2002, 12, 31)
            ],
            'close': [41.5, 71.9, 61.7, 131.4, 151.3],
        }))

    bt = BackTest(
        data,
        callbacks=[
            MinAmountChecker(
                buy_dict={
                    '000001': [dt(1999, 1, 1), dt(2001, 1, 1)],
                    '000002': [dt(1998, 12, 31)]
                },
                sell_dict={'000001': [dt(2000, 1, 1),
                                      dt(2002, 1, 1)]},
            )
        ])
    bt.calc_trade_history()
    assert bt._BackTest__get_buy_avg_price('000001') == (0.0, 0.0)
    assert bt._BackTest__get_buy_avg_price('000002') == (41.5, 100.0)
    assert not bt.history_df.empty
    assert '000001' not in bt.available_hold_df.index
    assert bt.available_hold_df['000002'] != 0
    assert not bt.available_hold_df.empty
    # hold_table=bt.hold_table()
    # assert 100==hold_table['000002']
    # assert 0==hold_table['000001']
    assert not bt.hold_price_cur_df.empty
    assert 41.5 == bt.hold_price_cur_df.loc['000002']['buy_price']
    assert 100 == bt.hold_price_cur_df.loc['000002']['amount']
    print(bt.report())
    bt = BackTest(data,
                  callbacks=[
                      MinAmountChecker(
                          buy_dict={
                              '000001': [dt(1999, 1, 1),
                                         dt(2001, 1, 1)],
                              '000002': [dt(1998, 12, 31)]
                          },
                          sell_dict={'000001': [dt(2000, 1, 1)]},
                      )
                  ])
    bt.calc_trade_history()
    assert not bt.history_df.empty
    assert not bt.available_hold_df.empty
    assert bt.available_hold_df['000001'] != 0
    assert bt.available_hold_df['000002'] != 0
    assert bt._BackTest__get_buy_avg_price('000001') == (13.4, 100.0)
    assert bt._BackTest__get_buy_avg_price('000002') == (41.5, 100.0)
    # hold_table=bt.hold_table()
    # assert 100==hold_table['000002']
    # assert 100==hold_table['000001']
    assert not bt.hold_price_cur_df.empty
    assert 41.5 == bt.hold_price_cur_df.loc['000002']['buy_price']
    assert 13.4 == bt.hold_price_cur_df.loc['000001']['buy_price']
    print(bt.report())
    print(bt.hold_time().to_string())