import os import numpy as np import pandas as pd import matplotlib.pyplot as plt from typing import Dict def calculate_pnl( product: str, exchange: str, data: pd.DataFrame, max_pos: int, open_threshold: float, close_threshold: float ): """ 此函数用于计算一天的收益。 :param product: 交易品种 :param exchange: 交易所 :param data: 交易数据, 必须包含 predict, bid, ask, bid_vol, ask_vol 这五列数据 :param max_pos: 最大仓位 :param open_threshold: 开仓阈值 :param close_threshold: 平仓阈值 :return: {"profit": 毛利润, "commission": 手续费, "trade_n": 交易手数} """ # load other data ############################## change dir here ############################## fee_data = pd.read_csv("./other_data/commission-2023-12-18.csv") volume_data = pd.read_csv("./other_data/DailyMarketVolume_20231218.csv") inst_data = pd.read_csv("./other_data/instrument-2023-12-18.csv") ############################################################################# lock_position_list = ["IC", "IF", "IH", "IM", "AP", "lh", "sn", "ni", ] lock_position = product in lock_position_list if exchange in ["SHFE", "DCE", "GFEX"]: product = product.lower() else: product = product.upper() tmp = volume_data[volume_data['ProductId'] == product] if len(tmp) != 1: raise ValueError("There is {} volume record for {} ".format(len(tmp), product)) symbol = str(tmp['Symbol1'].values[0]) tmp = fee_data[fee_data["InstrumentID"] == symbol] if len(tmp) < 1: raise ValueError("{} commission record less than 1".format(symbol)) open_ratio = tmp["OpenRatioByMoney"].values[0] open_fix = tmp["OpenRatioByVolume"].values[0] if lock_position: close_ratio = tmp["CloseRatioByMoney"].values[0] close_fix = tmp["CloseRatioByVolume"].values[0] else: close_ratio = tmp["CloseTodayRatioByMoney"].values[0] close_fix = tmp["CloseTodayRatioByVolume"].values[0] inst_data = inst_data[inst_data["InstrumentID"] == symbol] assert len(inst_data) > 0, "{} inst record is 0".format(symbol) multiplier = int(inst_data["VolumeMultiple"].values[0]) px_tick = inst_data["PriceTick"].values[0] val_multip = multiplier * px_tick # calculate trade information # predict = data["predict"].values predict = data["predict_0226"].values bid = data["bid"].values ask = data["ask"].values bid_vol = data["bid_vol"].values ask_vol = data["ask_vol"].values cur_pos = 0 revenue = [0] average_profit = 0 commission = [0] all_account = [0] trade_n = 0 for i in range(predict.shape[0]): trade_signal = predict[i] ord_amt = 0 dir = None if cur_pos == 0: if trade_signal >= open_threshold: dir = "BUY" ord_amt = min(max_pos, ask_vol[i]) elif trade_signal <= -1 * open_threshold: dir = "SELL" ord_amt = min(max_pos, bid_vol[i]) elif cur_pos > 0: if trade_signal >= open_threshold and cur_pos < max_pos: dir = "BUY" ord_amt = max(0, min(max_pos - cur_pos, ask_vol[i])) elif trade_signal <= -1 * close_threshold: dir = "SELL" if trade_signal <= -1 * open_threshold: ord_amt = min(max_pos + cur_pos, bid_vol[0]) else: ord_amt = min(cur_pos, bid_vol[0]) else: # cur_pos < 0 if trade_signal <= -1 * open_threshold and cur_pos > -max_pos: dir = "SELL" ord_amt = max(0, min(max_pos + cur_pos, bid_vol[i])) elif trade_signal >= close_threshold: dir = "BUY" if trade_signal >= open_threshold: ord_amt = min(max_pos - cur_pos, ask_vol[i]) else: ord_amt = min(-cur_pos, ask_vol[i]) if ord_amt != 0 and dir is not None: # calculate pnl & update cur_pos if dir == 'SELL': px = bid[i] if cur_pos >= ord_amt: diff = px * ord_amt - average_profit * ord_amt commission.append(ord_amt * (px * close_ratio * val_multip + close_fix)) elif cur_pos <= 0: diff = 0 average_profit = (average_profit * abs(cur_pos) + ord_amt * px) / (abs(cur_pos) + ord_amt) commission.append(ord_amt * (px * open_ratio * val_multip + open_fix)) else: diff = px * abs(cur_pos) - average_profit * abs(cur_pos) commission.append(abs(cur_pos) * (px * close_ratio * val_multip + close_fix) + \ (ord_amt - abs(cur_pos)) * (px * open_ratio * val_multip + open_fix)) average_profit = px cur_pos = cur_pos - ord_amt all_account.append(cur_pos) elif dir == 'BUY': px = ask[i] if cur_pos <= ord_amt * -1: diff = average_profit * ord_amt - px * ord_amt commission.append(ord_amt * (px * close_ratio * val_multip + close_fix)) elif cur_pos >= 0: diff = 0 average_profit = (average_profit * abs(cur_pos) + ord_amt * px) / (abs(cur_pos) + ord_amt) commission.append(ord_amt * (px * open_ratio * val_multip + open_fix)) else: diff = average_profit * abs(cur_pos) - px * abs(cur_pos) commission.append(abs(cur_pos) * (px * close_ratio * val_multip + close_fix) + \ (ord_amt - abs(cur_pos)) * (px * open_ratio * val_multip + open_fix)) average_profit = px cur_pos = cur_pos + ord_amt all_account.append(cur_pos) else: raise ValueError("Unknown dir: {}".format(dir)) revenue.append(diff * val_multip) trade_n += ord_amt return {"revenue": revenue, "commission": commission, "trade_n": trade_n} # "position": all_account, def sharpe_ratio( pl: np.ndarray, base_rate: float = 0, ): """ 此代码用于计算夏普率 """ if len(pl) == 0: return np.NaN pl2 = pl - base_rate pl2_std = np.std(pl2) if pl2_std == 0: return np.NaN return np.mean(pl2) / pl2_std def sharpe_ratio_day( net_pl: np.ndarray ): """ 此代码用于计算夏普率(按照天数计算) """ n_days = len(net_pl) if n_days == 0: return np.NaN mult = float(len(net_pl)) * 250 / n_days return sharpe_ratio(net_pl) * np.sqrt(mult) def plot_pnl(revenue: np.ndarray, commission: np.ndarray, rebate_ratio: float, save_dir: str, title: str): """ 此代码用于绘制收益曲线 """ plt.figure(figsize = (10, 5)) plt.step(range(len(revenue)), np.cumsum(revenue), color = 'g', label = 'Revenue') plt.step(range(len(commission)), np.cumsum(commission), color = 'r', label = 'Commission') plt.step(range(len(revenue)), np.cumsum(revenue) - np.cumsum(commission), color = 'b', linestyle = '--', label = 'Profit') plt.step(range(len(revenue)), np.cumsum(revenue) - np.cumsum(commission * (1 - rebate_ratio)), color = 'b', label = 'Net P&L') plt.axhline(y = 0, color = 'g', linestyle = '--') plt.title(title) plt.legend() plt.savefig(save_dir) def portfolio( trade_data: Dict, max_pos: int, threshold: tuple, rebate_ratio: float, save_dir: str, ): """ 此代码用于生成回测报告(csv文件)和绘制收益曲线 :param trade_data: 交易数据 :param max_pos: 最大仓位 :param threshold: 交易阈值 :param rebate_ratio: 手续费返还比例 :param save_dir: 报告保存路径 :return: None """ start_day = min(list(trade_data.keys())) end_day = max(list(trade_data.keys())) days_n = len(list(trade_data.keys())) revenue_list = [] commission_list = [] trade_n = 0 for x in trade_data.values(): revenue_list.append(sum(x["revenue"])) commission_list.append(sum(x["commission"])) trade_n += x["trade_n"] net_pnl_list = np.array(revenue_list) - (1 - rebate_ratio) * np.array(commission_list) sr = sharpe_ratio_day(net_pnl_list) report_path = os.path.join(save_dir, "backtest.csv") figure_path = os.path.join(save_dir, "figures") os.makedirs(figure_path, exist_ok = True) if os.path.exists(report_path): report = pd.read_csv(report_path) else: report = pd.DataFrame( columns = [ "StartDay", "EndDay", "Days", "Threshold", "MaxPos", "Revenue", "Fee", "Profit", "PNL", "AvgPnl", "Sharpe", "Trades", "TO", ] ) new_row = pd.DataFrame( { "StartDay": [start_day], # 第一个交易日 "EndDay": [end_day], # 最后一个交易日 "Days": [days_n], # 交易日数量 "Threshold": [threshold], # 交易阈值 "MaxPos": [max_pos], # 最大仓位 "Revenue": [sum(revenue_list)], # 费前收益 "Fee": [sum(commission_list)], # 手续费 "Profit": [sum(revenue_list) - sum(commission_list)], # 费后收益 "PNL": [sum(net_pnl_list)], # 净收益(加上手续费返还:PNL = Profit + rebate_ratio * Fee) "AvgPnl": [sum(net_pnl_list) / trade_n if trade_n > 0 else 0], # 每笔交易的净利润 "Sharpe": [sr], # 夏普率 "Trades": [trade_n], # 交易手数 "TO": [trade_n / days_n / max_pos if trade_n > 0 else 0], # 换手率 } ) report = pd.concat([report, new_row], ignore_index = True) report.to_csv(report_path, index = False) plot_pnl( revenue = np.concatenate([x["revenue"] for x in trade_data.values()]), commission = np.concatenate([x["commission"] for x in trade_data.values()]), rebate_ratio = rebate_ratio, save_dir = os.path.join(figure_path, "backtest_{:.03f}_{:.03f}.png".format(threshold[0], threshold[1])), title = "Backtest {} - {}".format(str(start_day), str(end_day)) )