用python选择一只股票,设计基于均线、回归、两种机器学习方法的交易策略,画出包含基 于这四种策略和买入并持有策略的股票收益率走势图,解释并将图片输出为 “3.1”;使用 Train-Test Split 检验这五种策略并画图,解释并将图片输出为 “3.2”。
时间: 2024-02-20 11:56:08 浏览: 154
好的,我可以为您提供完整的代码示例来实现这个任务。
首先还是需要安装Tushare库和pandas库。可以使用以下命令进行安装:
```python
!pip install tushare
!pip install pandas
```
然后,选择一只股票,例如阿里巴巴(股票代码为BABA),使用Tushare库获取历史数据,并进行数据处理和分析。
```python
import tushare as ts
import pandas as pd
# 获取股票数据
df = ts.get_k_data('BABA', start='2010-01-01', end='2021-08-31')
df.index = pd.to_datetime(df['date']) # 将日期作为索引
df = df[['open', 'close']] # 只保留开盘价和收盘价两列
df.columns = ['Open', 'Close'] # 重命名列名
# 计算移动平均线
df['MA5'] = df['Close'].rolling(5).mean()
df['MA20'] = df['Close'].rolling(20).mean()
# 计算回归分析指标
from sklearn.linear_model import LinearRegression
X = df[['Open']]
y = df['Close']
reg = LinearRegression().fit(X, y)
df['Predict'] = reg.predict(X)
# 计算机器学习指标
from sklearn.ensemble import RandomForestRegressor
from sklearn.svm import SVR
X = df[['Open', 'Close', 'MA5', 'MA20']]
y = df['Close']
rf = RandomForestRegressor(n_estimators=100, random_state=1).fit(X, y)
df['RF_Predict'] = rf.predict(X)
svm = SVR(kernel='rbf', C=1e3, gamma=0.1).fit(X, y)
df['SVM_Predict'] = svm.predict(X)
# 计算收益率
df['Buy_Hold_Returns'] = df['Close'].pct_change()
df['MA_Returns'] = df['Close'].pct_change().shift(-1) * df['MA5'].apply(lambda x: 1 if df['Close'][-1] > x else -1)
df['Reg_Returns'] = df['Close'].pct_change().shift(-1) * df['Predict'].apply(lambda x: 1 if df['Close'][-1] > x else -1)
df['RF_Returns'] = df['Close'].pct_change().shift(-1) * df['RF_Predict'].apply(lambda x: 1 if df['Close'][-1] > x else -1)
df['SVM_Returns'] = df['Close'].pct_change().shift(-1) * df['SVM_Predict'].apply(lambda x: 1 if df['Close'][-1] > x else -1)
# 绘制收益率走势图
import matplotlib.pyplot as plt
df[['Buy_Hold_Returns', 'MA_Returns', 'Reg_Returns', 'RF_Returns', 'SVM_Returns']].cumsum().plot(figsize=(10, 6))
plt.title('Stock Returns')
plt.xlabel('Date')
plt.ylabel('Cumulative Returns')
plt.savefig('3.1.png')
```
以上代码实现了基于移动平均线、回归、随机森林和支持向量机的交易策略,并绘制了收益率走势图。
接下来,可以使用Train-Test Split方法检验这五种策略,并绘制检验结果图。
```python
from sklearn.model_selection import train_test_split
# 划分训练集和测试集
train_df, test_df = train_test_split(df, test_size=0.2, shuffle=False)
# 训练集收益率
train_df['Buy_Hold_Returns'] = train_df['Close'].pct_change()
train_df['MA_Returns'] = train_df['Close'].pct_change().shift(-1) * train_df['MA5'].apply(lambda x: 1 if train_df['Close'][-1] > x else -1)
train_df['Reg_Returns'] = train_df['Close'].pct_change().shift(-1) * train_df['Predict'].apply(lambda x: 1 if train_df['Close'][-1] > x else -1)
train_df['RF_Returns'] = train_df['Close'].pct_change().shift(-1) * train_df['RF_Predict'].apply(lambda x: 1 if train_df['Close'][-1] > x else -1)
train_df['SVM_Returns'] = train_df['Close'].pct_change().shift(-1) * train_df['SVM_Predict'].apply(lambda x: 1 if train_df['Close'][-1] > x else -1)
# 测试集收益率
test_df['Buy_Hold_Returns'] = test_df['Close'].pct_change()
test_df['MA_Returns'] = test_df['Close'].pct_change().shift(-1) * test_df['MA5'].apply(lambda x: 1 if test_df['Close'][-1] > x else -1)
test_df['Reg_Returns'] = test_df['Close'].pct_change().shift(-1) * test_df['Predict'].apply(lambda x: 1 if test_df['Close'][-1] > x else -1)
test_df['RF_Returns'] = test_df['Close'].pct_change().shift(-1) * test_df['RF_Predict'].apply(lambda x: 1 if test_df['Close'][-1] > x else -1)
test_df['SVM_Returns'] = test_df['Close'].pct_change().shift(-1) * test_df['SVM_Predict'].apply(lambda x: 1 if test_df['Close'][-1] > x else -1)
# 绘制检验结果图
train_df[['Buy_Hold_Returns', 'MA_Returns', 'Reg_Returns', 'RF_Returns', 'SVM_Returns']].cumsum().plot(figsize=(10, 6))
plt.title('Train Performance')
plt.xlabel('Date')
plt.ylabel('Cumulative Returns')
plt.savefig('3.2_train.png')
test_df[['Buy_Hold_Returns', 'MA_Returns', 'Reg_Returns', 'RF_Returns', 'SVM_Returns']].cumsum().plot(figsize=(10, 6))
plt.title('Test Performance')
plt.xlabel('Date')
plt.ylabel('Cumulative Returns')
plt.savefig('3.2_test.png')
```
以上代码基于Train-Test Split方法检验了这五种策略,并绘制了检验结果图。您可以根据需要自行调整参数和指标,并使用其他机器学习算法进行交易策略的设计。
阅读全文