自行获取随意一只股票的数据,并用python进行均线交易策略构建
时间: 2023-06-17 21:05:40 浏览: 45
好的,我可以使用 tushare 库来获取股票数据,并使用 pandas、matplotlib 和 numpy 库进行均线交易策略构建。以下是具体步骤:
1. 安装 tushare 库
在终端或命令提示符中输入以下命令:
```
pip install tushare
```
2. 导入库
```python
import tushare as ts
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
```
3. 获取股票数据
```python
# 获取股票数据
df = ts.get_k_data('600519', start='2019-01-01', end='2020-12-31')
```
上面的代码中,`get_k_data` 函数用来获取股票数据,参数中的 `start` 和 `end` 分别表示开始时间和结束时间,`600519` 表示贵州茅台的股票代码。
4. 计算均线
```python
# 计算5日均线和20日均线
df['ma5'] = df['close'].rolling(5).mean()
df['ma20'] = df['close'].rolling(20).mean()
```
上面的代码中,`rolling` 函数用来进行滚动计算,参数 `5` 和 `20` 分别表示 5 日均线和 20 日均线。
5. 构建交易策略
```python
# 计算均线交叉信号
df['signal'] = np.where(df['ma5'] > df['ma20'], 1, 0)
df['position'] = df['signal'].shift(1)
# 计算每天的收益率
df['pct_change'] = df['close'].pct_change()
# 计算策略收益率
df['strategy_return'] = df['pct_change'] * df['position']
# 计算累计收益率
df['cum_strategy_return'] = (1 + df['strategy_return']).cumprod()
```
上面的代码中,`np.where` 函数用来判断均线交叉信号,如果 5 日均线大于 20 日均线,则信号为 1,否则为 0。`shift` 函数用来将信号向前移动一天,作为当天的持仓仓位。`pct_change` 函数用来计算每天的收益率。`strategy_return` 则表示当天的策略收益率,即买入或卖出当天的收益率。`cum_strategy_return` 则表示累计收益率。
6. 绘制图表
```python
# 绘制股价和均线图
plt.plot(df['date'], df['close'], label='Close')
plt.plot(df['date'], df['ma5'], label='MA5')
plt.plot(df['date'], df['ma20'], label='MA20')
plt.legend()
# 绘制策略收益率图
plt.figure()
plt.plot(df['date'], df['cum_strategy_return'])
plt.title('Cumulative Strategy Return')
plt.show()
```
上面的代码中,`plot` 函数用来绘制股价和均线图,`legend` 函数用来添加图例。`figure` 函数用来创建新的图表,`title` 函数用来添加标题,`show` 函数用来显示图表。
最终的完整代码如下:
```python
import tushare as ts
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 获取股票数据
df = ts.get_k_data('600519', start='2019-01-01', end='2020-12-31')
# 计算5日均线和20日均线
df['ma5'] = df['close'].rolling(5).mean()
df['ma20'] = df['close'].rolling(20).mean()
# 计算均线交叉信号
df['signal'] = np.where(df['ma5'] > df['ma20'], 1, 0)
df['position'] = df['signal'].shift(1)
# 计算每天的收益率
df['pct_change'] = df['close'].pct_change()
# 计算策略收益率
df['strategy_return'] = df['pct_change'] * df['position']
# 计算累计收益率
df['cum_strategy_return'] = (1 + df['strategy_return']).cumprod()
# 绘制股价和均线图
plt.plot(df['date'], df['close'], label='Close')
plt.plot(df['date'], df['ma5'], label='MA5')
plt.plot(df['date'], df['ma20'], label='MA20')
plt.legend()
# 绘制策略收益率图
plt.figure()
plt.plot(df['date'], df['cum_strategy_return'])
plt.title('Cumulative Strategy Return')
plt.show()
```
运行上面的代码后,即可得到股价和均线图以及策略收益率图。