0


【2022美赛 C题 交易策略】Python实现的baseline

目录

更新时间:2022-2-20 10:30

相关链接

完整代码和参考文献下载
https://mianbaoduo.com/o/bread/YpeclJhr

1 题目

要求开发一个模型, 这个模型只使用到目前为止的过去的每日价格流来确定,每天应该买入、 持有还是卖出他们投资组合中的资产。
2016 年 9 月 11 日, 将从 1000 美元开始。 将使用五年交易期, 从 2016 年 9 月 11 日到2021 年 9 月 10 日。 在每个交易日, 交易者的投资组合将包括现金、 黄金和比特币[C, G, B],分别是美元、 金衡盎司和比特币。 初始状态为[1000,0,0]。 每笔交易(购买或销售)的佣金是交易金额的α%。 假设

  1. α
  2. g
  3. o
  4. l
  5. d
  6. \alpha _{gold}
  7. αgold​= 1%,
  8. α
  9. b
  10. i
  11. t
  12. c
  13. o
  14. i
  15. n
  16. \alpha_{bitcoin}
  17. αbitcoin = 2%。 持有资产没有成本。

请注意, 比特币可以每天交易, 但黄金只在市场开放的日子交易(即周末不交易), 这反映在定价数据文件LBMA-GOLD.csv 和 BCHAIN-MKPRU.csv 中。 你的模型应该考虑到这个交易计划, 但在建模过程中你只能使用其中之一。

  • 开发一个模型, 仅根据当天的价格数据给出最佳的每日交易策略。 使用你的模型和策略, 在 2021 年 9 月 10 日最初的 1000 美元投资价值多少?
  • 提供证据证明你的模型提供了最佳策略。
  • 确定该策略对交易成本的敏感度。 交易成本如何影响战略和结果?
  • 将你的策略、 模型和结果以一份不超过两页的备忘录的形式传达给交易者。 注意: 您的 PDF 总页数不超过 25 页, 解决方案应包括:
  • 一页摘要表。 目录。 完整的解决方案。 一到两页附录。 参考文献。> 注:MCM 竞赛有 25 页的限制。 您提交的所有方面都计入 25 页的限制(摘要页、 目录、 参考文献和任何附录)。 必须在你的报告中标注你的想法、 图像和其他材料的来源引用

2 思路解析

3 Python 实现

3.1 数据分析和预处理

(1)数据分析

  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  1. gold = pd.read_csv('./data/LBMA-GOLD.csv')
  2. bitcoin = pd.read_csv('./data/BCHAIN-MKPRU.csv')
  1. gold.info()

<class ‘pandas.core.frame.DataFrame’>

RangeIndex: 1265 entries, 0 to 1264 Data columns (total 2 columns):

Column Non-Null Count Dtype — ------ -------------- -----

0 Date 1265 non-null object

1 USD (PM) 1255 non-null float64

dtypes: float64(1), object(1)

  1. # 缺失值查看
  2. gold.isnull().any()

Date False

USD (PM) True

dtype: bool

黄金序列存在缺失值

  1. bitcoin.isnull().any()

Date False

Value False

dtype: bool

比特币序列没有缺失值

可视化数据

  1. x1 =range(len(gold))
  2. y1 = gold['USD (PM)']
  3. x2 =range(len(bitcoin))
  4. y2 = bitcoin['Value']
  5. plt.plot(x1,y1)

在这里插入图片描述
在这里插入图片描述

  1. plt.plot(x2,y2,color='r')

(2)数据预处理

黄金序列是有缺失值,且周末不存在数据,时间序列是中断的,以下采用插值法进行填充数据,将补充为完整的时间序列

  1. gold.index =list(pd.DatetimeIndex(gold.Date))
  2. gold_datalist = pd.date_range(start='2016-09-12',end='2021-09-10')
  3. ts = pd.Series(len(gold_datalist)*[np.nan],index=gold_datalist)
  4. gold_s = gold['USD (PM)']for i in gold.index:
  5. ts[i]= gold_s[i]# 线性插值法
  6. ts = ts.interpolate(method='linear')
  7. gold_df = ts.astype(float).to_frame()
  8. gold_df.rename(columns={0:'USD'},inplace=True)
  9. gold_df.sort_index()
  10. gold_df.index =range(len(gold_df))
  11. gold_df

补充完整后,黄金的时间序列有1825条数据

3.2 预测

(1)特征工程

  1. # 提取特征from tsfresh import extract_features, extract_relevant_features, select_features
  2. from tsfresh.utilities.dataframe_functions import impute
  3. gold_df['id']=range(len(gold_df))
  4. extracted_features = extract_features(gold_df,column_id='id')
  5. extracted_features.index = gold_df.index
  6. # 去除NAN特征
  7. extracted_features2 = impute(extracted_features)

构造训练集

  1. import re
  2. # 向未来移动一个时间步长
  3. timestep =1
  4. Y =list(gold_df['USD'][timestep:])
  5. X_t = extracted_features2[:-timestep]
  6. X = select_features(X_t, np.array(Y), fdr_level=0.5)
  7. X = X.rename(columns =lambda x:re.sub('[^A-Za-z0-9_]+','', x))

(2)模型训练预测

  1. # 划分30%作为测试集
  2. s =0.3
  3. tra_len =int((1-s)*len(X))
  4. test_len =len(X)-tra_len
  5. X_train, X_test, y_train, y_test = X[0:tra_len], X[-test_len:], Y[0:tra_len],Y[-test_len:]
  1. # 方法一import lightgbm as lgb
  2. # clf = lgb.LGBMRegressor(# learning_rate=0.01,# max_depth=-1,# n_estimators=5000,# boosting_type='gbdt',# random_state=2022,# objective='regression',# )# clf.fit(X=X_train, y=y_train, eval_metric='MSE', verbose=50)# y_predict = clf.predict(X_test)# 方法二from sklearn.model_selection import train_test_split
  3. from sklearn.linear_model import LinearRegression
  4. import matplotlib.pyplot as plt
  5. linreg = LinearRegression()
  6. model = linreg.fit(X_train, y_train)
  7. y_pred = linreg.predict(X_test)

预测及输出评价指标

  1. from sklearn import metrics
  2. defmetric_regresion(y_true,y_pre):
  3. mse = metrics.mean_squared_error(y_true,y_pre)
  4. mae = metrics.mean_absolute_error(y_true,y_pre)
  5. rmse = np.sqrt(metrics.mean_squared_error(y_true,y_pre))# RMSE
  6. r2 = metrics.r2_score(y_true,y_pre)print('MSE:{}'.format(mse))print('MAE:{}'.format(mae))print('RMSE:{}'.format(rmse))print('R2:{}'.format(r2))
  7. metric_regresion(y_test,y_pred)

MSE:267.91294723114646

MAE:10.630377450265746

RMSE:16.368046530699576

R2:0.9707506268528148

可视化预测结果

  1. import matplotlib.pyplot as plt
  2. plt.figure()
  3. plt.plot(range(len(y_pred[100:180])), y_pred[100:180],'b', label="预测")
  4. plt.plot(range(len(y_test[100:180])), y_test[100:180],'r', label="原始")
  5. plt.legend(loc="upper right", prop={'size':15})
  6. plt.show()

在这里插入图片描述

3.3 进阶的预测方案和代码

在以上的同一个下载链接中

完整思路下载
在这里插入图片描述

3.3 动态规划

3.3.1 思路方案

符号说明

  1. w
  2. 1
  3. w_1
  4. w1​,
  5. w
  6. 2
  7. w_2
  8. w2 初始买入比例
  9. P
  10. t
  11. P_t
  12. Pt​,
  13. P
  14. t
  15. 1
  16. P_{t-1}
  17. Pt1 前后一天价格

diff 前后一天价格差

  1. Y
  2. t
  3. Y_t
  4. Yt 变化收益

b% 中途卖出比例(也是买入比例)
目标函数:

  1. m
  2. a
  3. x
  4. max
  5. max
  6. Y
  7. t
  8. Y_t
  9. Yt =
  10. W
  11. 1
  12. W_1
  13. W1
  14. P
  15. P_
  16. P黄​+
  17. W
  18. 2
  19. W_2
  20. W2
  21. P
  22. P_
  23. P比​

约束条件:
1、

  1. C
  2. =
  3. W
  4. 1
  5. ×
  6. P
  7. ×
  8. b
  9. %
  10. ×
  11. 1
  12. %
  13. +
  14. W
  15. i
  16. ×
  17. P
  18. ×
  19. b
  20. %
  21. ×
  22. 2
  23. %
  24. C=W_1×P × b\% ×1\%+W_i × P × b \% × 2 \%
  25. C=W1​×P×b1%+Wi​×P×b2%(成本约束)(买出卖出成本)

2、

  1. X
  2. i
  3. =
  4. {
  5. 0
  6. x
  7. 0
  8. =周末
  9. 1
  10. x
  11. 1
  12. !=周末
  13. X_i= \begin{cases} 0& \text{$x_0$=周末}\\ 1& \text{$x_1$ !=周末} \end{cases}
  14. Xi​={01x0​=周末x1 !=周末​

3、diff=

  1. P
  2. t
  3. P_t
  4. Pt​-
  5. P
  6. t
  7. 1
  8. P_{t-1}
  9. Pt1 (持有会带来的成本)

4、

  1. 0
  2. r
  3. 1
  4. 0 \leq r \leq 1
  5. 0r1 风险系数约束(可用预测模型的置信区间权衡风险)

模型讲解:
完整思路下载

3.3.2 Python实现

待上传…


本文转载自: https://blog.csdn.net/weixin_43935696/article/details/123024884
版权归原作者 Better Bench 所有, 如有侵权,请联系我们删除。

“【2022美赛 C题 交易策略】Python实现的baseline”的评论:

还没有评论