5、Python量化交易-回测收益计算

前言

  • 上一篇我们已经通过padas导入bar回测数据,这篇我们通过导入的ticks数据进行回测的实现
  • 生成1:matplotlib盈亏柱状图
  • 生成2:k线图
  • 生成3:投影订单进出场时间与价格到k线图

一、回测的主方法

if __name__ == '__main__':
    ticks = get_ticks_for_backtesting("E:\\Downloads\\600036_data\\600036_ticks.csv",
                                      "E:\\Downloads\\600036_data\\600036_5m.csv")  # 获取回测数据
    ast = AstockTrading('ma')
    ast.run_backtestting(ticks)  # 运行回测数据
    print('ast._current_orders:')
    print(ast._current_orders)
    print("-------------------------------------")
    print('ast._history_orders:')
    print(ast._history_orders)

    # 使用matplotlib绘制盈亏柱状图
    profit_orders = 0  # 盈利的交易数
    loss_orders = 0  # 亏损的交易数
    orders = ast._history_orders
    for key in orders.keys():
        if orders[key]['pnl'] >= 0:
            profit_orders += 1
        else:
            loss_orders += 1
    win_rate = profit_orders / len(orders)
    loss_rate = loss_orders / len(orders)
    # T = transpose
    orders_df = pd.DataFrame(orders).T
    orders_df.loc[:, 'pnl'].plot.bar()
    plt.show()

    # 使用 mplfinance 绘制k线图:订单交易价格与时间
    bar5 = pd.read_csv("E:\\Downloads\\600036_data\\600036_5m.csv",
                       parse_dates=['datetime']
                       )
    bar5.loc[:, 'datetime'] = [date2num(x) for x in bar5.loc[:, 'datetime']]

    fig, ax = plt.subplots()
    candlestick_ohlc(
        ax,
        quotes=bar5.values,
        width=0.2,
        colorup="r",
        colordown='g',
        alpha=1.0,
    )

    # put orders in candle sticks
    for index, row in orders_df.iterrows():
        ax.plot(
            [row['open_datetime'], row['close_datetime']],
            [row['open_price'], row['close_price']],
            color='darkblue',
            marker='o',
        )
    plt.show()

二、回测实现

1 - 获取回测数据ticks

def get_ticks_for_backtesting(tick_path, bar_path):
    """
    :func: get ticks for backtesting, need two params
    :param1 tick_path: 生成的回测数据路径
            csv file with tick data,
            when there is not tick data,
            use bat_path to create tick data
            example: "E:\\Downloads\\600036_data\\600036_ticks.csv"
    :param2 bar_path: 历史数据的tick路径
            csv file with bar data,
            used in creating tick data
            example: "E:\\Downloads\\600036_data\\600036_5m.csv"
    :return: ticks in list with tuples in it, such as
            [(datetime, last_price), (datetime, last_price)]
    """
    if os.path.exists(tick_path):  # 如果已存在回测数据,直接读取回测数据ticks
        ticks = pd.read_csv(
            tick_path,
            parse_dates=['datetime'],
            index_col='datetime'
        )

        tick_list = []
        for index, row in ticks.iterrows():
            tick_list.append((index, row[0]))

        ticks = np.array(tick_list)
    else:
        bar_5m = pd.read_csv(bar_path)  # 使用pandas读取csv数据
        ticks = []

        for index, row in bar_5m.iterrows():  # 根据不同的开盘价设置步长
            if row['open'] < 30:
                step = 0.01
            elif row['open'] < 60:
                step = 0.03
            elif row['open'] < 90:
                step = 0.05
            else:
                step = 0.1
            # in case of np.arrange(30, 30.11, 0.02), (open, high, step)
            # we will not have 30.11 as the highest price,
            # we might not catch high when step is more than 0.01
            # that is why me need: arr = np.append(arr, row['high']) and
            #   arr = np.append(arr, row['low'])
            arr = np.arange(row['open'], row['high'], step)  # 按步长生成从open到high的数据
            arr = np.append(arr, row['high'])  # 这个是为了弥补步长的不对等会漏掉high
            arr = np.append(arr, np.arange(row['open'] - step, row['low'], -step))  # 按步长生成从open到low的数据
            arr = np.append(arr, row['low'])  # 这个是为了弥补步长的不对等会漏掉low
            arr = np.append(arr, row['close'])

            i = 0
            dt = parser.parse(row['datetime']) - timedelta(minutes=5)
            for item in arr:
                ticks.append((dt + timedelta(seconds=0.1 * i), item))  # 将数据时间模拟到0.1秒递进
                i += 1
        tick_df = pd.DataFrame(ticks, columns=['datetime', 'price'])
        tick_df.to_csv(tick_path, index=0)  # 保存到csv回测数据中
    return ticks

2 - 运行回测

    def run_backtestting(self, ticks):
        """
        :method: ticks will be used to generate bars,
                when bars is long enough, call strategy()
        :param ticks: list with (datetime, price) in the list
        :return: none
        """
        for tick in ticks:
            self.bar_generator_for_backtesting
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无休止符

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值