File size: 2,571 Bytes
4cbde8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"""
运行此脚本可以得到回测结果。
你需要先修改此脚本中的data_dir和save_dir、以及calculate_pnl.py中的fee_data、volume_data、inst_data五个地方的路径为你本地机器的路径,
之后就可以运行成功。
"""

from calculate_pnl import calculate_pnl, portfolio
import pandas as pd
import os
from datetime import date, timedelta


product_para = {
    # "FG": {"exchange": "CZCE", "open_threshold": 0.88, "close_threshold": 0.792},
    # "sc": {"exchange": "DCE", "open_threshold": 0.46, "close_threshold": 0.322},
    "FG": {"exchange": "CZCE", "open_threshold": 0.25, "close_threshold": 0.15},
    "sc": {"exchange": "DCE", "open_threshold": 0.46, "close_threshold": 0.322},
}
############################## change dir here ##############################
# data_dir = "./generate_data/"  # 保存数据的路径
# save_dir = "./backtest/"     # 保存回测结果的路径

data_dir = "./res/"  # 保存数据的路径
save_dir = "./backtest/"     # 保存回测结果的路径
#############################################################################

if __name__ == "__main__":
    # product parameters
    product = "FG"  # 品种名称
    exchange = product_para[product]["exchange"]  # 交易所
    open_threshold = product_para[product]["open_threshold"]  # 开仓阈值
    close_threshold = product_para[product]["close_threshold"]  # 平仓阈值
    max_pos = 1  # 最大仓位

    # backtest parameters
    start_day = date(2023, 12, 18)  # 回测起始日
    end_day = date(2023, 12, 18)   # 回测结束日
    rebate_ratio = 0.4  # 手续费返还比例,0.4代表40%的手续费最后会被返还给给账户

    # backtest
    day = start_day
    backtest_data = {}
    while day <= end_day:
        path = os.path.join(data_dir, product, "{}.csv".format(day))
        print(path, os.path.exists(path))
        if not os.path.exists(path):
            day += timedelta(days = 1)
            continue
        tmp = pd.read_csv(path)
        backtest_data[day] = calculate_pnl(
            product = product,
            exchange = exchange,
            data = tmp,
            max_pos = max_pos,
            open_threshold = open_threshold,
            close_threshold = close_threshold,
        )
        day += timedelta(days = 1)
        continue

    # generate pnl data
    portfolio(
        trade_data = backtest_data,
        max_pos = max_pos,
        threshold = (open_threshold, close_threshold),
        rebate_ratio = rebate_ratio,
        save_dir = os.path.join(save_dir, product),
    )