Upload 4 files
Browse files- calculate_pnl.py +252 -0
- demo.py +68 -0
- notebook/data_eda.ipynb +341 -0
- notebook/nn_baseline.ipynb +259 -0
calculate_pnl.py
ADDED
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import numpy as np
|
3 |
+
import pandas as pd
|
4 |
+
import matplotlib.pyplot as plt
|
5 |
+
from typing import Dict
|
6 |
+
|
7 |
+
|
8 |
+
def calculate_pnl(
|
9 |
+
product: str,
|
10 |
+
exchange: str,
|
11 |
+
data: pd.DataFrame,
|
12 |
+
max_pos: int,
|
13 |
+
open_threshold: float,
|
14 |
+
close_threshold: float
|
15 |
+
):
|
16 |
+
"""
|
17 |
+
此函数用于计算一天的收益。
|
18 |
+
:param product: 交易品种
|
19 |
+
:param exchange: 交易所
|
20 |
+
:param data: 交易数据, 必须包含 predict, bid, ask, bid_vol, ask_vol 这五列数据
|
21 |
+
:param max_pos: 最大仓位
|
22 |
+
:param open_threshold: 开仓阈值
|
23 |
+
:param close_threshold: 平仓阈值
|
24 |
+
:return: {"profit": 毛利润, "commission": 手续费, "trade_n": 交易手数}
|
25 |
+
"""
|
26 |
+
# load other data
|
27 |
+
############################## change dir here ##############################
|
28 |
+
fee_data = pd.read_csv("./other_data/commission-2023-12-18.csv")
|
29 |
+
volume_data = pd.read_csv("./other_data/DailyMarketVolume_20231218.csv")
|
30 |
+
inst_data = pd.read_csv("./other_data/instrument-2023-12-18.csv")
|
31 |
+
#############################################################################
|
32 |
+
lock_position_list = ["IC", "IF", "IH", "IM", "AP", "lh", "sn", "ni", ]
|
33 |
+
lock_position = product in lock_position_list
|
34 |
+
if exchange in ["SHFE", "DCE", "GFEX"]:
|
35 |
+
product = product.lower()
|
36 |
+
else:
|
37 |
+
product = product.upper()
|
38 |
+
tmp = volume_data[volume_data['ProductId'] == product]
|
39 |
+
if len(tmp) != 1:
|
40 |
+
raise ValueError("There is {} volume record for {} ".format(len(tmp), product))
|
41 |
+
symbol = str(tmp['Symbol1'].values[0])
|
42 |
+
tmp = fee_data[fee_data["InstrumentID"] == symbol]
|
43 |
+
if len(tmp) < 1:
|
44 |
+
raise ValueError("{} commission record less than 1".format(symbol))
|
45 |
+
open_ratio = tmp["OpenRatioByMoney"].values[0]
|
46 |
+
open_fix = tmp["OpenRatioByVolume"].values[0]
|
47 |
+
if lock_position:
|
48 |
+
close_ratio = tmp["CloseRatioByMoney"].values[0]
|
49 |
+
close_fix = tmp["CloseRatioByVolume"].values[0]
|
50 |
+
else:
|
51 |
+
close_ratio = tmp["CloseTodayRatioByMoney"].values[0]
|
52 |
+
close_fix = tmp["CloseTodayRatioByVolume"].values[0]
|
53 |
+
inst_data = inst_data[inst_data["InstrumentID"] == symbol]
|
54 |
+
assert len(inst_data) > 0, "{} inst record is 0".format(symbol)
|
55 |
+
multiplier = int(inst_data["VolumeMultiple"].values[0])
|
56 |
+
px_tick = inst_data["PriceTick"].values[0]
|
57 |
+
val_multip = multiplier * px_tick
|
58 |
+
# calculate trade information
|
59 |
+
# predict = data["predict"].values
|
60 |
+
predict = data["predict_0226"].values
|
61 |
+
bid = data["bid"].values
|
62 |
+
ask = data["ask"].values
|
63 |
+
bid_vol = data["bid_vol"].values
|
64 |
+
ask_vol = data["ask_vol"].values
|
65 |
+
cur_pos = 0
|
66 |
+
revenue = [0]
|
67 |
+
average_profit = 0
|
68 |
+
commission = [0]
|
69 |
+
all_account = [0]
|
70 |
+
trade_n = 0
|
71 |
+
for i in range(predict.shape[0]):
|
72 |
+
trade_signal = predict[i]
|
73 |
+
ord_amt = 0
|
74 |
+
dir = None
|
75 |
+
if cur_pos == 0:
|
76 |
+
if trade_signal >= open_threshold:
|
77 |
+
dir = "BUY"
|
78 |
+
ord_amt = min(max_pos, ask_vol[i])
|
79 |
+
elif trade_signal <= -1 * open_threshold:
|
80 |
+
dir = "SELL"
|
81 |
+
ord_amt = min(max_pos, bid_vol[i])
|
82 |
+
elif cur_pos > 0:
|
83 |
+
if trade_signal >= open_threshold and cur_pos < max_pos:
|
84 |
+
dir = "BUY"
|
85 |
+
ord_amt = max(0, min(max_pos - cur_pos, ask_vol[i]))
|
86 |
+
elif trade_signal <= -1 * close_threshold:
|
87 |
+
dir = "SELL"
|
88 |
+
if trade_signal <= -1 * open_threshold:
|
89 |
+
ord_amt = min(max_pos + cur_pos, bid_vol[0])
|
90 |
+
else:
|
91 |
+
ord_amt = min(cur_pos, bid_vol[0])
|
92 |
+
else: # cur_pos < 0
|
93 |
+
if trade_signal <= -1 * open_threshold and cur_pos > -max_pos:
|
94 |
+
dir = "SELL"
|
95 |
+
ord_amt = max(0, min(max_pos + cur_pos, bid_vol[i]))
|
96 |
+
elif trade_signal >= close_threshold:
|
97 |
+
dir = "BUY"
|
98 |
+
if trade_signal >= open_threshold:
|
99 |
+
ord_amt = min(max_pos - cur_pos, ask_vol[i])
|
100 |
+
else:
|
101 |
+
ord_amt = min(-cur_pos, ask_vol[i])
|
102 |
+
if ord_amt != 0 and dir is not None:
|
103 |
+
# calculate pnl & update cur_pos
|
104 |
+
if dir == 'SELL':
|
105 |
+
px = bid[i]
|
106 |
+
if cur_pos >= ord_amt:
|
107 |
+
diff = px * ord_amt - average_profit * ord_amt
|
108 |
+
commission.append(ord_amt * (px * close_ratio * val_multip + close_fix))
|
109 |
+
elif cur_pos <= 0:
|
110 |
+
diff = 0
|
111 |
+
average_profit = (average_profit * abs(cur_pos) + ord_amt * px) / (abs(cur_pos) + ord_amt)
|
112 |
+
commission.append(ord_amt * (px * open_ratio * val_multip + open_fix))
|
113 |
+
else:
|
114 |
+
diff = px * abs(cur_pos) - average_profit * abs(cur_pos)
|
115 |
+
commission.append(abs(cur_pos) * (px * close_ratio * val_multip + close_fix) + \
|
116 |
+
(ord_amt - abs(cur_pos)) * (px * open_ratio * val_multip + open_fix))
|
117 |
+
average_profit = px
|
118 |
+
cur_pos = cur_pos - ord_amt
|
119 |
+
all_account.append(cur_pos)
|
120 |
+
elif dir == 'BUY':
|
121 |
+
px = ask[i]
|
122 |
+
if cur_pos <= ord_amt * -1:
|
123 |
+
diff = average_profit * ord_amt - px * ord_amt
|
124 |
+
commission.append(ord_amt * (px * close_ratio * val_multip + close_fix))
|
125 |
+
elif cur_pos >= 0:
|
126 |
+
diff = 0
|
127 |
+
average_profit = (average_profit * abs(cur_pos) + ord_amt * px) / (abs(cur_pos) + ord_amt)
|
128 |
+
commission.append(ord_amt * (px * open_ratio * val_multip + open_fix))
|
129 |
+
else:
|
130 |
+
diff = average_profit * abs(cur_pos) - px * abs(cur_pos)
|
131 |
+
commission.append(abs(cur_pos) * (px * close_ratio * val_multip + close_fix) + \
|
132 |
+
(ord_amt - abs(cur_pos)) * (px * open_ratio * val_multip + open_fix))
|
133 |
+
average_profit = px
|
134 |
+
cur_pos = cur_pos + ord_amt
|
135 |
+
all_account.append(cur_pos)
|
136 |
+
else:
|
137 |
+
raise ValueError("Unknown dir: {}".format(dir))
|
138 |
+
revenue.append(diff * val_multip)
|
139 |
+
trade_n += ord_amt
|
140 |
+
return {"revenue": revenue, "commission": commission, "trade_n": trade_n} # "position": all_account,
|
141 |
+
|
142 |
+
|
143 |
+
def sharpe_ratio(
|
144 |
+
pl: np.ndarray,
|
145 |
+
base_rate: float = 0,
|
146 |
+
):
|
147 |
+
"""
|
148 |
+
此代码用于计算夏普率
|
149 |
+
"""
|
150 |
+
if len(pl) == 0:
|
151 |
+
return np.NaN
|
152 |
+
pl2 = pl - base_rate
|
153 |
+
pl2_std = np.std(pl2)
|
154 |
+
if pl2_std == 0:
|
155 |
+
return np.NaN
|
156 |
+
return np.mean(pl2) / pl2_std
|
157 |
+
|
158 |
+
|
159 |
+
def sharpe_ratio_day(
|
160 |
+
net_pl: np.ndarray
|
161 |
+
):
|
162 |
+
"""
|
163 |
+
此代码用于计算夏普率(按照天数计算)
|
164 |
+
"""
|
165 |
+
n_days = len(net_pl)
|
166 |
+
if n_days == 0:
|
167 |
+
return np.NaN
|
168 |
+
mult = float(len(net_pl)) * 250 / n_days
|
169 |
+
return sharpe_ratio(net_pl) * np.sqrt(mult)
|
170 |
+
|
171 |
+
|
172 |
+
def plot_pnl(revenue: np.ndarray, commission: np.ndarray, rebate_ratio: float, save_dir: str, title: str):
|
173 |
+
"""
|
174 |
+
此代码用于绘制收益曲线
|
175 |
+
"""
|
176 |
+
plt.figure(figsize = (10, 5))
|
177 |
+
plt.step(range(len(revenue)), np.cumsum(revenue), color = 'g', label = 'Revenue')
|
178 |
+
plt.step(range(len(commission)), np.cumsum(commission), color = 'r', label = 'Commission')
|
179 |
+
plt.step(range(len(revenue)), np.cumsum(revenue) - np.cumsum(commission), color = 'b', linestyle = '--', label = 'Profit')
|
180 |
+
plt.step(range(len(revenue)), np.cumsum(revenue) - np.cumsum(commission * (1 - rebate_ratio)), color = 'b', label = 'Net P&L')
|
181 |
+
plt.axhline(y = 0, color = 'g', linestyle = '--')
|
182 |
+
plt.title(title)
|
183 |
+
plt.legend()
|
184 |
+
plt.savefig(save_dir)
|
185 |
+
|
186 |
+
|
187 |
+
def portfolio(
|
188 |
+
trade_data: Dict,
|
189 |
+
max_pos: int,
|
190 |
+
threshold: tuple,
|
191 |
+
rebate_ratio: float,
|
192 |
+
save_dir: str,
|
193 |
+
):
|
194 |
+
"""
|
195 |
+
此代码用于生成回测报告(csv文件)和绘制收益曲线
|
196 |
+
:param trade_data: 交易数据
|
197 |
+
:param max_pos: 最大仓位
|
198 |
+
:param threshold: 交易阈值
|
199 |
+
:param rebate_ratio: 手续费返还比例
|
200 |
+
:param save_dir: 报告保存路径
|
201 |
+
:return: None
|
202 |
+
"""
|
203 |
+
start_day = min(list(trade_data.keys()))
|
204 |
+
end_day = max(list(trade_data.keys()))
|
205 |
+
days_n = len(list(trade_data.keys()))
|
206 |
+
revenue_list = []
|
207 |
+
commission_list = []
|
208 |
+
trade_n = 0
|
209 |
+
for x in trade_data.values():
|
210 |
+
revenue_list.append(sum(x["revenue"]))
|
211 |
+
commission_list.append(sum(x["commission"]))
|
212 |
+
trade_n += x["trade_n"]
|
213 |
+
net_pnl_list = np.array(revenue_list) - (1 - rebate_ratio) * np.array(commission_list)
|
214 |
+
sr = sharpe_ratio_day(net_pnl_list)
|
215 |
+
report_path = os.path.join(save_dir, "backtest.csv")
|
216 |
+
figure_path = os.path.join(save_dir, "figures")
|
217 |
+
os.makedirs(figure_path, exist_ok = True)
|
218 |
+
if os.path.exists(report_path):
|
219 |
+
report = pd.read_csv(report_path)
|
220 |
+
else:
|
221 |
+
report = pd.DataFrame(
|
222 |
+
columns = [
|
223 |
+
"StartDay", "EndDay", "Days", "Threshold", "MaxPos", "Revenue", "Fee", "Profit", "PNL",
|
224 |
+
"AvgPnl", "Sharpe", "Trades", "TO",
|
225 |
+
]
|
226 |
+
)
|
227 |
+
new_row = pd.DataFrame(
|
228 |
+
{
|
229 |
+
"StartDay": [start_day], # 第一个交易日
|
230 |
+
"EndDay": [end_day], # 最后一个交易日
|
231 |
+
"Days": [days_n], # 交易日数量
|
232 |
+
"Threshold": [threshold], # 交易阈值
|
233 |
+
"MaxPos": [max_pos], # 最大仓位
|
234 |
+
"Revenue": [sum(revenue_list)], # 费前收益
|
235 |
+
"Fee": [sum(commission_list)], # 手续费
|
236 |
+
"Profit": [sum(revenue_list) - sum(commission_list)], # 费后收益
|
237 |
+
"PNL": [sum(net_pnl_list)], # 净收益(加上手续费返还:PNL = Profit + rebate_ratio * Fee)
|
238 |
+
"AvgPnl": [sum(net_pnl_list) / trade_n if trade_n > 0 else 0], # 每笔交易的净利润
|
239 |
+
"Sharpe": [sr], # 夏普率
|
240 |
+
"Trades": [trade_n], # 交易手数
|
241 |
+
"TO": [trade_n / days_n / max_pos if trade_n > 0 else 0], # 换手率
|
242 |
+
}
|
243 |
+
)
|
244 |
+
report = pd.concat([report, new_row], ignore_index = True)
|
245 |
+
report.to_csv(report_path, index = False)
|
246 |
+
plot_pnl(
|
247 |
+
revenue = np.concatenate([x["revenue"] for x in trade_data.values()]),
|
248 |
+
commission = np.concatenate([x["commission"] for x in trade_data.values()]),
|
249 |
+
rebate_ratio = rebate_ratio,
|
250 |
+
save_dir = os.path.join(figure_path, "backtest_{:.03f}_{:.03f}.png".format(threshold[0], threshold[1])),
|
251 |
+
title = "Backtest {} - {}".format(str(start_day), str(end_day))
|
252 |
+
)
|
demo.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
运行此脚本可以得到回测结果。
|
3 |
+
你需要先修改此脚本中的data_dir和save_dir、以及calculate_pnl.py中的fee_data、volume_data、inst_data五个地方的路径为你本地机器的路径,
|
4 |
+
之后就可以运行成功。
|
5 |
+
"""
|
6 |
+
|
7 |
+
from calculate_pnl import calculate_pnl, portfolio
|
8 |
+
import pandas as pd
|
9 |
+
import os
|
10 |
+
from datetime import date, timedelta
|
11 |
+
|
12 |
+
|
13 |
+
product_para = {
|
14 |
+
# "FG": {"exchange": "CZCE", "open_threshold": 0.88, "close_threshold": 0.792},
|
15 |
+
# "sc": {"exchange": "DCE", "open_threshold": 0.46, "close_threshold": 0.322},
|
16 |
+
"FG": {"exchange": "CZCE", "open_threshold": 0.25, "close_threshold": 0.15},
|
17 |
+
"sc": {"exchange": "DCE", "open_threshold": 0.46, "close_threshold": 0.322},
|
18 |
+
}
|
19 |
+
############################## change dir here ##############################
|
20 |
+
# data_dir = "./generate_data/" # 保存数据的路径
|
21 |
+
# save_dir = "./backtest/" # 保存回测结果的路径
|
22 |
+
|
23 |
+
data_dir = "./res/" # 保存数据的路径
|
24 |
+
save_dir = "./backtest/" # 保存回测结果的路径
|
25 |
+
#############################################################################
|
26 |
+
|
27 |
+
if __name__ == "__main__":
|
28 |
+
# product parameters
|
29 |
+
product = "FG" # 品种名称
|
30 |
+
exchange = product_para[product]["exchange"] # 交易所
|
31 |
+
open_threshold = product_para[product]["open_threshold"] # 开仓阈值
|
32 |
+
close_threshold = product_para[product]["close_threshold"] # 平仓阈值
|
33 |
+
max_pos = 1 # 最大仓位
|
34 |
+
|
35 |
+
# backtest parameters
|
36 |
+
start_day = date(2023, 12, 18) # 回测起始日
|
37 |
+
end_day = date(2023, 12, 18) # 回测结束日
|
38 |
+
rebate_ratio = 0.4 # 手续费返还比例,0.4代表40%的手续费最后会被返还给给账户
|
39 |
+
|
40 |
+
# backtest
|
41 |
+
day = start_day
|
42 |
+
backtest_data = {}
|
43 |
+
while day <= end_day:
|
44 |
+
path = os.path.join(data_dir, product, "{}.csv".format(day))
|
45 |
+
print(path, os.path.exists(path))
|
46 |
+
if not os.path.exists(path):
|
47 |
+
day += timedelta(days = 1)
|
48 |
+
continue
|
49 |
+
tmp = pd.read_csv(path)
|
50 |
+
backtest_data[day] = calculate_pnl(
|
51 |
+
product = product,
|
52 |
+
exchange = exchange,
|
53 |
+
data = tmp,
|
54 |
+
max_pos = max_pos,
|
55 |
+
open_threshold = open_threshold,
|
56 |
+
close_threshold = close_threshold,
|
57 |
+
)
|
58 |
+
day += timedelta(days = 1)
|
59 |
+
continue
|
60 |
+
|
61 |
+
# generate pnl data
|
62 |
+
portfolio(
|
63 |
+
trade_data = backtest_data,
|
64 |
+
max_pos = max_pos,
|
65 |
+
threshold = (open_threshold, close_threshold),
|
66 |
+
rebate_ratio = rebate_ratio,
|
67 |
+
save_dir = os.path.join(save_dir, product),
|
68 |
+
)
|
notebook/data_eda.ipynb
ADDED
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 2,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [],
|
8 |
+
"source": [
|
9 |
+
"import os, sys, json, collections\n",
|
10 |
+
"import pandas as pd\n",
|
11 |
+
"import numpy as np"
|
12 |
+
]
|
13 |
+
},
|
14 |
+
{
|
15 |
+
"cell_type": "markdown",
|
16 |
+
"metadata": {},
|
17 |
+
"source": [
|
18 |
+
"### FG(玻璃)数据"
|
19 |
+
]
|
20 |
+
},
|
21 |
+
{
|
22 |
+
"cell_type": "code",
|
23 |
+
"execution_count": 6,
|
24 |
+
"metadata": {},
|
25 |
+
"outputs": [
|
26 |
+
{
|
27 |
+
"name": "stdout",
|
28 |
+
"output_type": "stream",
|
29 |
+
"text": [
|
30 |
+
"(80808, 127)\n"
|
31 |
+
]
|
32 |
+
},
|
33 |
+
{
|
34 |
+
"data": {
|
35 |
+
"text/html": [
|
36 |
+
"<div>\n",
|
37 |
+
"<style scoped>\n",
|
38 |
+
" .dataframe tbody tr th:only-of-type {\n",
|
39 |
+
" vertical-align: middle;\n",
|
40 |
+
" }\n",
|
41 |
+
"\n",
|
42 |
+
" .dataframe tbody tr th {\n",
|
43 |
+
" vertical-align: top;\n",
|
44 |
+
" }\n",
|
45 |
+
"\n",
|
46 |
+
" .dataframe thead th {\n",
|
47 |
+
" text-align: right;\n",
|
48 |
+
" }\n",
|
49 |
+
"</style>\n",
|
50 |
+
"<table border=\"1\" class=\"dataframe\">\n",
|
51 |
+
" <thead>\n",
|
52 |
+
" <tr style=\"text-align: right;\">\n",
|
53 |
+
" <th></th>\n",
|
54 |
+
" <th>Unnamed: 0</th>\n",
|
55 |
+
" <th>MidPxChange_1</th>\n",
|
56 |
+
" <th>MidPxChange_5</th>\n",
|
57 |
+
" <th>MidPxChange_10</th>\n",
|
58 |
+
" <th>MidPxChange_20</th>\n",
|
59 |
+
" <th>MidPxChange_50</th>\n",
|
60 |
+
" <th>MidPxChange_100</th>\n",
|
61 |
+
" <th>MidPxChange_200</th>\n",
|
62 |
+
" <th>MidPxVolRatio_1</th>\n",
|
63 |
+
" <th>MidPxVolRatio_5</th>\n",
|
64 |
+
" <th>...</th>\n",
|
65 |
+
" <th>label1</th>\n",
|
66 |
+
" <th>label2</th>\n",
|
67 |
+
" <th>last</th>\n",
|
68 |
+
" <th>bid</th>\n",
|
69 |
+
" <th>ask</th>\n",
|
70 |
+
" <th>bid_vol</th>\n",
|
71 |
+
" <th>ask_vol</th>\n",
|
72 |
+
" <th>volume</th>\n",
|
73 |
+
" <th>turnover</th>\n",
|
74 |
+
" <th>predict</th>\n",
|
75 |
+
" </tr>\n",
|
76 |
+
" </thead>\n",
|
77 |
+
" <tbody>\n",
|
78 |
+
" <tr>\n",
|
79 |
+
" <th>0</th>\n",
|
80 |
+
" <td>2023-05-31 21:00:00.500</td>\n",
|
81 |
+
" <td>-1.0</td>\n",
|
82 |
+
" <td>-1.0</td>\n",
|
83 |
+
" <td>-1.0</td>\n",
|
84 |
+
" <td>-1.0</td>\n",
|
85 |
+
" <td>-1.0</td>\n",
|
86 |
+
" <td>-1.0</td>\n",
|
87 |
+
" <td>-1.0</td>\n",
|
88 |
+
" <td>-0.00303</td>\n",
|
89 |
+
" <td>-0.003030</td>\n",
|
90 |
+
" <td>...</td>\n",
|
91 |
+
" <td>-7.0</td>\n",
|
92 |
+
" <td>-2.285714</td>\n",
|
93 |
+
" <td>1406.0</td>\n",
|
94 |
+
" <td>1405.0</td>\n",
|
95 |
+
" <td>1406.0</td>\n",
|
96 |
+
" <td>594.0</td>\n",
|
97 |
+
" <td>96.0</td>\n",
|
98 |
+
" <td>2502.0</td>\n",
|
99 |
+
" <td>3524194.0</td>\n",
|
100 |
+
" <td>0.245262</td>\n",
|
101 |
+
" </tr>\n",
|
102 |
+
" <tr>\n",
|
103 |
+
" <th>1</th>\n",
|
104 |
+
" <td>2023-05-31 21:00:00.750</td>\n",
|
105 |
+
" <td>0.0</td>\n",
|
106 |
+
" <td>-1.0</td>\n",
|
107 |
+
" <td>-1.0</td>\n",
|
108 |
+
" <td>-1.0</td>\n",
|
109 |
+
" <td>-1.0</td>\n",
|
110 |
+
" <td>-1.0</td>\n",
|
111 |
+
" <td>-1.0</td>\n",
|
112 |
+
" <td>0.00000</td>\n",
|
113 |
+
" <td>-0.001105</td>\n",
|
114 |
+
" <td>...</td>\n",
|
115 |
+
" <td>-7.0</td>\n",
|
116 |
+
" <td>-2.285714</td>\n",
|
117 |
+
" <td>1406.0</td>\n",
|
118 |
+
" <td>1405.0</td>\n",
|
119 |
+
" <td>1406.0</td>\n",
|
120 |
+
" <td>460.0</td>\n",
|
121 |
+
" <td>1102.0</td>\n",
|
122 |
+
" <td>3077.0</td>\n",
|
123 |
+
" <td>4332491.0</td>\n",
|
124 |
+
" <td>-0.709275</td>\n",
|
125 |
+
" </tr>\n",
|
126 |
+
" </tbody>\n",
|
127 |
+
"</table>\n",
|
128 |
+
"<p>2 rows × 127 columns</p>\n",
|
129 |
+
"</div>"
|
130 |
+
],
|
131 |
+
"text/plain": [
|
132 |
+
" Unnamed: 0 MidPxChange_1 MidPxChange_5 MidPxChange_10 \\\n",
|
133 |
+
"0 2023-05-31 21:00:00.500 -1.0 -1.0 -1.0 \n",
|
134 |
+
"1 2023-05-31 21:00:00.750 0.0 -1.0 -1.0 \n",
|
135 |
+
"\n",
|
136 |
+
" MidPxChange_20 MidPxChange_50 MidPxChange_100 MidPxChange_200 \\\n",
|
137 |
+
"0 -1.0 -1.0 -1.0 -1.0 \n",
|
138 |
+
"1 -1.0 -1.0 -1.0 -1.0 \n",
|
139 |
+
"\n",
|
140 |
+
" MidPxVolRatio_1 MidPxVolRatio_5 ... label1 label2 last bid \\\n",
|
141 |
+
"0 -0.00303 -0.003030 ... -7.0 -2.285714 1406.0 1405.0 \n",
|
142 |
+
"1 0.00000 -0.001105 ... -7.0 -2.285714 1406.0 1405.0 \n",
|
143 |
+
"\n",
|
144 |
+
" ask bid_vol ask_vol volume turnover predict \n",
|
145 |
+
"0 1406.0 594.0 96.0 2502.0 3524194.0 0.245262 \n",
|
146 |
+
"1 1406.0 460.0 1102.0 3077.0 4332491.0 -0.709275 \n",
|
147 |
+
"\n",
|
148 |
+
"[2 rows x 127 columns]"
|
149 |
+
]
|
150 |
+
},
|
151 |
+
"execution_count": 6,
|
152 |
+
"metadata": {},
|
153 |
+
"output_type": "execute_result"
|
154 |
+
}
|
155 |
+
],
|
156 |
+
"source": [
|
157 |
+
"filepath = '/Users/saidcalculationboy/Coding/GenWealth/data/generate_data/FG/2023-06-01.csv'\n",
|
158 |
+
"FG_1_df = pd.read_csv(filepath)\n",
|
159 |
+
"print(FG_1_df.shape)\n",
|
160 |
+
"FG_1_df.head(2)"
|
161 |
+
]
|
162 |
+
},
|
163 |
+
{
|
164 |
+
"cell_type": "code",
|
165 |
+
"execution_count": null,
|
166 |
+
"metadata": {},
|
167 |
+
"outputs": [],
|
168 |
+
"source": []
|
169 |
+
},
|
170 |
+
{
|
171 |
+
"cell_type": "code",
|
172 |
+
"execution_count": null,
|
173 |
+
"metadata": {},
|
174 |
+
"outputs": [],
|
175 |
+
"source": []
|
176 |
+
},
|
177 |
+
{
|
178 |
+
"cell_type": "code",
|
179 |
+
"execution_count": 7,
|
180 |
+
"metadata": {},
|
181 |
+
"outputs": [
|
182 |
+
{
|
183 |
+
"name": "stdout",
|
184 |
+
"output_type": "stream",
|
185 |
+
"text": [
|
186 |
+
"(84453, 127)\n"
|
187 |
+
]
|
188 |
+
},
|
189 |
+
{
|
190 |
+
"data": {
|
191 |
+
"text/html": [
|
192 |
+
"<div>\n",
|
193 |
+
"<style scoped>\n",
|
194 |
+
" .dataframe tbody tr th:only-of-type {\n",
|
195 |
+
" vertical-align: middle;\n",
|
196 |
+
" }\n",
|
197 |
+
"\n",
|
198 |
+
" .dataframe tbody tr th {\n",
|
199 |
+
" vertical-align: top;\n",
|
200 |
+
" }\n",
|
201 |
+
"\n",
|
202 |
+
" .dataframe thead th {\n",
|
203 |
+
" text-align: right;\n",
|
204 |
+
" }\n",
|
205 |
+
"</style>\n",
|
206 |
+
"<table border=\"1\" class=\"dataframe\">\n",
|
207 |
+
" <thead>\n",
|
208 |
+
" <tr style=\"text-align: right;\">\n",
|
209 |
+
" <th></th>\n",
|
210 |
+
" <th>Unnamed: 0</th>\n",
|
211 |
+
" <th>MidPxChange_1</th>\n",
|
212 |
+
" <th>MidPxChange_5</th>\n",
|
213 |
+
" <th>MidPxChange_10</th>\n",
|
214 |
+
" <th>MidPxChange_20</th>\n",
|
215 |
+
" <th>MidPxChange_50</th>\n",
|
216 |
+
" <th>MidPxChange_100</th>\n",
|
217 |
+
" <th>MidPxChange_200</th>\n",
|
218 |
+
" <th>MidPxVolRatio_1</th>\n",
|
219 |
+
" <th>MidPxVolRatio_5</th>\n",
|
220 |
+
" <th>...</th>\n",
|
221 |
+
" <th>label1</th>\n",
|
222 |
+
" <th>label2</th>\n",
|
223 |
+
" <th>last</th>\n",
|
224 |
+
" <th>bid</th>\n",
|
225 |
+
" <th>ask</th>\n",
|
226 |
+
" <th>bid_vol</th>\n",
|
227 |
+
" <th>ask_vol</th>\n",
|
228 |
+
" <th>volume</th>\n",
|
229 |
+
" <th>turnover</th>\n",
|
230 |
+
" <th>predict</th>\n",
|
231 |
+
" </tr>\n",
|
232 |
+
" </thead>\n",
|
233 |
+
" <tbody>\n",
|
234 |
+
" <tr>\n",
|
235 |
+
" <th>0</th>\n",
|
236 |
+
" <td>2023-05-31 21:00:01.000</td>\n",
|
237 |
+
" <td>0.5</td>\n",
|
238 |
+
" <td>0.5</td>\n",
|
239 |
+
" <td>0.5</td>\n",
|
240 |
+
" <td>0.5</td>\n",
|
241 |
+
" <td>0.5</td>\n",
|
242 |
+
" <td>0.5</td>\n",
|
243 |
+
" <td>0.5</td>\n",
|
244 |
+
" <td>0.019231</td>\n",
|
245 |
+
" <td>0.019231</td>\n",
|
246 |
+
" <td>...</td>\n",
|
247 |
+
" <td>5.142857</td>\n",
|
248 |
+
" <td>5.142857</td>\n",
|
249 |
+
" <td>4905.0</td>\n",
|
250 |
+
" <td>4901.0</td>\n",
|
251 |
+
" <td>4905.0</td>\n",
|
252 |
+
" <td>4.0</td>\n",
|
253 |
+
" <td>5.0</td>\n",
|
254 |
+
" <td>559.0</td>\n",
|
255 |
+
" <td>2744938.0</td>\n",
|
256 |
+
" <td>-0.014487</td>\n",
|
257 |
+
" </tr>\n",
|
258 |
+
" <tr>\n",
|
259 |
+
" <th>1</th>\n",
|
260 |
+
" <td>2023-05-31 21:00:01.250</td>\n",
|
261 |
+
" <td>-0.5</td>\n",
|
262 |
+
" <td>0.0</td>\n",
|
263 |
+
" <td>0.0</td>\n",
|
264 |
+
" <td>0.0</td>\n",
|
265 |
+
" <td>0.0</td>\n",
|
266 |
+
" <td>0.0</td>\n",
|
267 |
+
" <td>0.0</td>\n",
|
268 |
+
" <td>-0.006173</td>\n",
|
269 |
+
" <td>0.000000</td>\n",
|
270 |
+
" <td>...</td>\n",
|
271 |
+
" <td>6.035714</td>\n",
|
272 |
+
" <td>6.035714</td>\n",
|
273 |
+
" <td>4904.0</td>\n",
|
274 |
+
" <td>4902.0</td>\n",
|
275 |
+
" <td>4903.0</td>\n",
|
276 |
+
" <td>1.0</td>\n",
|
277 |
+
" <td>3.0</td>\n",
|
278 |
+
" <td>640.0</td>\n",
|
279 |
+
" <td>3141997.0</td>\n",
|
280 |
+
" <td>-0.093558</td>\n",
|
281 |
+
" </tr>\n",
|
282 |
+
" </tbody>\n",
|
283 |
+
"</table>\n",
|
284 |
+
"<p>2 rows × 127 columns</p>\n",
|
285 |
+
"</div>"
|
286 |
+
],
|
287 |
+
"text/plain": [
|
288 |
+
" Unnamed: 0 MidPxChange_1 MidPxChange_5 MidPxChange_10 \\\n",
|
289 |
+
"0 2023-05-31 21:00:01.000 0.5 0.5 0.5 \n",
|
290 |
+
"1 2023-05-31 21:00:01.250 -0.5 0.0 0.0 \n",
|
291 |
+
"\n",
|
292 |
+
" MidPxChange_20 MidPxChange_50 MidPxChange_100 MidPxChange_200 \\\n",
|
293 |
+
"0 0.5 0.5 0.5 0.5 \n",
|
294 |
+
"1 0.0 0.0 0.0 0.0 \n",
|
295 |
+
"\n",
|
296 |
+
" MidPxVolRatio_1 MidPxVolRatio_5 ... label1 label2 last bid \\\n",
|
297 |
+
"0 0.019231 0.019231 ... 5.142857 5.142857 4905.0 4901.0 \n",
|
298 |
+
"1 -0.006173 0.000000 ... 6.035714 6.035714 4904.0 4902.0 \n",
|
299 |
+
"\n",
|
300 |
+
" ask bid_vol ask_vol volume turnover predict \n",
|
301 |
+
"0 4905.0 4.0 5.0 559.0 2744938.0 -0.014487 \n",
|
302 |
+
"1 4903.0 1.0 3.0 640.0 3141997.0 -0.093558 \n",
|
303 |
+
"\n",
|
304 |
+
"[2 rows x 127 columns]"
|
305 |
+
]
|
306 |
+
},
|
307 |
+
"execution_count": 7,
|
308 |
+
"metadata": {},
|
309 |
+
"output_type": "execute_result"
|
310 |
+
}
|
311 |
+
],
|
312 |
+
"source": [
|
313 |
+
"filepath = '/Users/saidcalculationboy/Coding/GenWealth/data/generate_data/sc/2023-06-01.csv'\n",
|
314 |
+
"sc_1_df = pd.read_csv(filepath)\n",
|
315 |
+
"print(sc_1_df.shape)\n",
|
316 |
+
"sc_1_df.head(2)"
|
317 |
+
]
|
318 |
+
}
|
319 |
+
],
|
320 |
+
"metadata": {
|
321 |
+
"kernelspec": {
|
322 |
+
"display_name": "pytorch",
|
323 |
+
"language": "python",
|
324 |
+
"name": "python3"
|
325 |
+
},
|
326 |
+
"language_info": {
|
327 |
+
"codemirror_mode": {
|
328 |
+
"name": "ipython",
|
329 |
+
"version": 3
|
330 |
+
},
|
331 |
+
"file_extension": ".py",
|
332 |
+
"mimetype": "text/x-python",
|
333 |
+
"name": "python",
|
334 |
+
"nbconvert_exporter": "python",
|
335 |
+
"pygments_lexer": "ipython3",
|
336 |
+
"version": "3.8.12"
|
337 |
+
}
|
338 |
+
},
|
339 |
+
"nbformat": 4,
|
340 |
+
"nbformat_minor": 2
|
341 |
+
}
|
notebook/nn_baseline.ipynb
ADDED
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 5,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [],
|
8 |
+
"source": [
|
9 |
+
"import pandas as pd\n",
|
10 |
+
"from sklearn.model_selection import train_test_split\n",
|
11 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
12 |
+
"from tensorflow.keras.models import Sequential\n",
|
13 |
+
"from tensorflow.keras.layers import Dense"
|
14 |
+
]
|
15 |
+
},
|
16 |
+
{
|
17 |
+
"cell_type": "code",
|
18 |
+
"execution_count": 7,
|
19 |
+
"metadata": {},
|
20 |
+
"outputs": [
|
21 |
+
{
|
22 |
+
"name": "stdout",
|
23 |
+
"output_type": "stream",
|
24 |
+
"text": [
|
25 |
+
"Epoch 1/10\n",
|
26 |
+
"2526/2526 [==============================] - 2s 757us/step - loss: 0.6998 - val_loss: 0.9270\n",
|
27 |
+
"Epoch 2/10\n",
|
28 |
+
"2526/2526 [==============================] - 2s 745us/step - loss: 0.7014 - val_loss: 0.9254\n",
|
29 |
+
"Epoch 3/10\n",
|
30 |
+
"2526/2526 [==============================] - 2s 647us/step - loss: 0.6917 - val_loss: 0.9253\n",
|
31 |
+
"Epoch 4/10\n",
|
32 |
+
"2526/2526 [==============================] - 2s 657us/step - loss: 0.6858 - val_loss: 0.9270\n",
|
33 |
+
"Epoch 5/10\n",
|
34 |
+
"2526/2526 [==============================] - 2s 718us/step - loss: 0.6889 - val_loss: 0.9264\n",
|
35 |
+
"Epoch 6/10\n",
|
36 |
+
"2526/2526 [==============================] - 2s 730us/step - loss: 0.6945 - val_loss: 0.9289\n",
|
37 |
+
"Epoch 7/10\n",
|
38 |
+
"2526/2526 [==============================] - 2s 651us/step - loss: 0.6867 - val_loss: 0.9274\n",
|
39 |
+
"Epoch 8/10\n",
|
40 |
+
"2526/2526 [==============================] - 2s 672us/step - loss: 0.6895 - val_loss: 0.9267\n",
|
41 |
+
"Epoch 9/10\n",
|
42 |
+
"2526/2526 [==============================] - 2s 656us/step - loss: 0.6938 - val_loss: 0.9278\n",
|
43 |
+
"Epoch 10/10\n",
|
44 |
+
"2526/2526 [==============================] - 2s 634us/step - loss: 0.6906 - val_loss: 0.9264\n",
|
45 |
+
"2539/2539 [==============================] - 1s 334us/step - loss: 0.9264\n",
|
46 |
+
"Test Loss: 0.9263737201690674\n"
|
47 |
+
]
|
48 |
+
}
|
49 |
+
],
|
50 |
+
"source": [
|
51 |
+
"# 读取数据\n",
|
52 |
+
"train_data = pd.read_csv('../generate_data/FG/2023-06-01.csv')\n",
|
53 |
+
"test_data = pd.read_csv('../generate_data/FG/2023-12-18.csv')\n",
|
54 |
+
"\n",
|
55 |
+
"# 选择因子\n",
|
56 |
+
"selected_factors = ['MidPxChange_1', 'MidPxVolRatio_1']\n",
|
57 |
+
"X_train = train_data[selected_factors] # 选择你认为合适的因子列\n",
|
58 |
+
"y_train = train_data['label1']\n",
|
59 |
+
"X_test = test_data[selected_factors]\n",
|
60 |
+
"y_test = test_data['label1']\n",
|
61 |
+
"\n",
|
62 |
+
"\n",
|
63 |
+
"# 数据标准化\n",
|
64 |
+
"scaler = StandardScaler()\n",
|
65 |
+
"X_train_scaled = scaler.fit_transform(X_train)\n",
|
66 |
+
"X_test_scaled = scaler.transform(X_test)\n",
|
67 |
+
"\n",
|
68 |
+
"# 构建神经网络模型\n",
|
69 |
+
"model = Sequential([\n",
|
70 |
+
" Dense(64, activation='relu', input_shape=(X_train_scaled.shape[1],)),\n",
|
71 |
+
" Dense(32, activation='relu'),\n",
|
72 |
+
" Dense(1) # 输出层,因为是回归问题,所以没有激活函数\n",
|
73 |
+
"])\n",
|
74 |
+
"\n",
|
75 |
+
"# 编译模型\n",
|
76 |
+
"model.compile(optimizer='adam', loss='mean_squared_error')\n",
|
77 |
+
"\n",
|
78 |
+
"# 训练模型\n",
|
79 |
+
"model.fit(X_train_scaled, y_train, epochs=10, batch_size=32, validation_data=(X_test_scaled, y_test))\n",
|
80 |
+
"\n",
|
81 |
+
"# 评估模型\n",
|
82 |
+
"loss = model.evaluate(X_test_scaled, y_test)\n",
|
83 |
+
"print('Test Loss:', loss)"
|
84 |
+
]
|
85 |
+
},
|
86 |
+
{
|
87 |
+
"cell_type": "code",
|
88 |
+
"execution_count": 8,
|
89 |
+
"metadata": {},
|
90 |
+
"outputs": [],
|
91 |
+
"source": [
|
92 |
+
"predictions = model.predict(X_test)\n",
|
93 |
+
"test_data['predict_0226'] = predictions"
|
94 |
+
]
|
95 |
+
},
|
96 |
+
{
|
97 |
+
"cell_type": "code",
|
98 |
+
"execution_count": 10,
|
99 |
+
"metadata": {},
|
100 |
+
"outputs": [],
|
101 |
+
"source": [
|
102 |
+
"test_data.to_csv('/Users/saidcalculationboy/Coding/GenWealth/data/res/FG/2023-12-18.csv')"
|
103 |
+
]
|
104 |
+
},
|
105 |
+
{
|
106 |
+
"cell_type": "code",
|
107 |
+
"execution_count": 12,
|
108 |
+
"metadata": {},
|
109 |
+
"outputs": [
|
110 |
+
{
|
111 |
+
"data": {
|
112 |
+
"text/html": [
|
113 |
+
"<div>\n",
|
114 |
+
"<style scoped>\n",
|
115 |
+
" .dataframe tbody tr th:only-of-type {\n",
|
116 |
+
" vertical-align: middle;\n",
|
117 |
+
" }\n",
|
118 |
+
"\n",
|
119 |
+
" .dataframe tbody tr th {\n",
|
120 |
+
" vertical-align: top;\n",
|
121 |
+
" }\n",
|
122 |
+
"\n",
|
123 |
+
" .dataframe thead th {\n",
|
124 |
+
" text-align: right;\n",
|
125 |
+
" }\n",
|
126 |
+
"</style>\n",
|
127 |
+
"<table border=\"1\" class=\"dataframe\">\n",
|
128 |
+
" <thead>\n",
|
129 |
+
" <tr style=\"text-align: right;\">\n",
|
130 |
+
" <th></th>\n",
|
131 |
+
" <th>Unnamed: 0</th>\n",
|
132 |
+
" <th>MidPxChange_1</th>\n",
|
133 |
+
" <th>MidPxChange_5</th>\n",
|
134 |
+
" <th>MidPxChange_10</th>\n",
|
135 |
+
" <th>MidPxChange_20</th>\n",
|
136 |
+
" <th>MidPxChange_50</th>\n",
|
137 |
+
" <th>MidPxChange_100</th>\n",
|
138 |
+
" <th>MidPxChange_200</th>\n",
|
139 |
+
" <th>MidPxVolRatio_1</th>\n",
|
140 |
+
" <th>MidPxVolRatio_5</th>\n",
|
141 |
+
" <th>...</th>\n",
|
142 |
+
" <th>label2</th>\n",
|
143 |
+
" <th>last</th>\n",
|
144 |
+
" <th>bid</th>\n",
|
145 |
+
" <th>ask</th>\n",
|
146 |
+
" <th>bid_vol</th>\n",
|
147 |
+
" <th>ask_vol</th>\n",
|
148 |
+
" <th>volume</th>\n",
|
149 |
+
" <th>turnover</th>\n",
|
150 |
+
" <th>predict</th>\n",
|
151 |
+
" <th>predict_0226</th>\n",
|
152 |
+
" </tr>\n",
|
153 |
+
" </thead>\n",
|
154 |
+
" <tbody>\n",
|
155 |
+
" <tr>\n",
|
156 |
+
" <th>0</th>\n",
|
157 |
+
" <td>2023-12-17 21:00:00.250</td>\n",
|
158 |
+
" <td>-2.0</td>\n",
|
159 |
+
" <td>-2.0</td>\n",
|
160 |
+
" <td>-2.0</td>\n",
|
161 |
+
" <td>-2.0</td>\n",
|
162 |
+
" <td>-2.0</td>\n",
|
163 |
+
" <td>-2.0</td>\n",
|
164 |
+
" <td>-2.0</td>\n",
|
165 |
+
" <td>-0.001403</td>\n",
|
166 |
+
" <td>-0.001403</td>\n",
|
167 |
+
" <td>...</td>\n",
|
168 |
+
" <td>8.1</td>\n",
|
169 |
+
" <td>1807.0</td>\n",
|
170 |
+
" <td>1807.0</td>\n",
|
171 |
+
" <td>1808.0</td>\n",
|
172 |
+
" <td>75.0</td>\n",
|
173 |
+
" <td>47.0</td>\n",
|
174 |
+
" <td>4007.0</td>\n",
|
175 |
+
" <td>7245815.0</td>\n",
|
176 |
+
" <td>0.269611</td>\n",
|
177 |
+
" <td>0.190654</td>\n",
|
178 |
+
" </tr>\n",
|
179 |
+
" <tr>\n",
|
180 |
+
" <th>1</th>\n",
|
181 |
+
" <td>2023-12-17 21:00:00.500</td>\n",
|
182 |
+
" <td>0.0</td>\n",
|
183 |
+
" <td>-2.0</td>\n",
|
184 |
+
" <td>-2.0</td>\n",
|
185 |
+
" <td>-2.0</td>\n",
|
186 |
+
" <td>-2.0</td>\n",
|
187 |
+
" <td>-2.0</td>\n",
|
188 |
+
" <td>-2.0</td>\n",
|
189 |
+
" <td>0.000000</td>\n",
|
190 |
+
" <td>-0.001218</td>\n",
|
191 |
+
" <td>...</td>\n",
|
192 |
+
" <td>8.1</td>\n",
|
193 |
+
" <td>1807.0</td>\n",
|
194 |
+
" <td>1807.0</td>\n",
|
195 |
+
" <td>1808.0</td>\n",
|
196 |
+
" <td>25.0</td>\n",
|
197 |
+
" <td>12.0</td>\n",
|
198 |
+
" <td>4223.0</td>\n",
|
199 |
+
" <td>7636347.0</td>\n",
|
200 |
+
" <td>0.889756</td>\n",
|
201 |
+
" <td>0.027161</td>\n",
|
202 |
+
" </tr>\n",
|
203 |
+
" </tbody>\n",
|
204 |
+
"</table>\n",
|
205 |
+
"<p>2 rows × 128 columns</p>\n",
|
206 |
+
"</div>"
|
207 |
+
],
|
208 |
+
"text/plain": [
|
209 |
+
" Unnamed: 0 MidPxChange_1 MidPxChange_5 MidPxChange_10 \\\n",
|
210 |
+
"0 2023-12-17 21:00:00.250 -2.0 -2.0 -2.0 \n",
|
211 |
+
"1 2023-12-17 21:00:00.500 0.0 -2.0 -2.0 \n",
|
212 |
+
"\n",
|
213 |
+
" MidPxChange_20 MidPxChange_50 MidPxChange_100 MidPxChange_200 \\\n",
|
214 |
+
"0 -2.0 -2.0 -2.0 -2.0 \n",
|
215 |
+
"1 -2.0 -2.0 -2.0 -2.0 \n",
|
216 |
+
"\n",
|
217 |
+
" MidPxVolRatio_1 MidPxVolRatio_5 ... label2 last bid ask \\\n",
|
218 |
+
"0 -0.001403 -0.001403 ... 8.1 1807.0 1807.0 1808.0 \n",
|
219 |
+
"1 0.000000 -0.001218 ... 8.1 1807.0 1807.0 1808.0 \n",
|
220 |
+
"\n",
|
221 |
+
" bid_vol ask_vol volume turnover predict predict_0226 \n",
|
222 |
+
"0 75.0 47.0 4007.0 7245815.0 0.269611 0.190654 \n",
|
223 |
+
"1 25.0 12.0 4223.0 7636347.0 0.889756 0.027161 \n",
|
224 |
+
"\n",
|
225 |
+
"[2 rows x 128 columns]"
|
226 |
+
]
|
227 |
+
},
|
228 |
+
"execution_count": 12,
|
229 |
+
"metadata": {},
|
230 |
+
"output_type": "execute_result"
|
231 |
+
}
|
232 |
+
],
|
233 |
+
"source": [
|
234 |
+
"test_data.head(2)"
|
235 |
+
]
|
236 |
+
}
|
237 |
+
],
|
238 |
+
"metadata": {
|
239 |
+
"kernelspec": {
|
240 |
+
"display_name": "pytorch",
|
241 |
+
"language": "python",
|
242 |
+
"name": "python3"
|
243 |
+
},
|
244 |
+
"language_info": {
|
245 |
+
"codemirror_mode": {
|
246 |
+
"name": "ipython",
|
247 |
+
"version": 3
|
248 |
+
},
|
249 |
+
"file_extension": ".py",
|
250 |
+
"mimetype": "text/x-python",
|
251 |
+
"name": "python",
|
252 |
+
"nbconvert_exporter": "python",
|
253 |
+
"pygments_lexer": "ipython3",
|
254 |
+
"version": "3.8.12"
|
255 |
+
}
|
256 |
+
},
|
257 |
+
"nbformat": 4,
|
258 |
+
"nbformat_minor": 2
|
259 |
+
}
|