用python写一段机器算法分析股票数据的代码
时间: 2023-05-10 11:56:12 浏览: 97
用Python做股市数据分析
非常感谢您的提问。以下是一段用 Python 编写的机器算法分析股票数据的代码:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# 读取股票数据
df = pd.read_csv('stock_data.csv')
# 计算收益率
df['return'] = df['close'].pct_change()
# 计算移动平均线
df['ma5'] = df['close'].rolling(window=5).mean()
df['ma20'] = df['close'].rolling(window=20).mean()
# 计算布林带
df['std'] = df['close'].rolling(window=20).std()
df['upper'] = df['ma20'] + 2 * df['std']
df['lower'] = df['ma20'] - 2 * df['std']
# 计算MACD指标
df['ema12'] = df['close'].ewm(span=12).mean()
df['ema26'] = df['close'].ewm(span=26).mean()
df['macd'] = df['ema12'] - df['ema26']
df['signal'] = df['macd'].ewm(span=9).mean()
# 计算RSI指标
delta = df['close'].diff()
gain = delta.where(delta > 0, 0)
loss = -delta.where(delta < 0, 0)
avg_gain = gain.rolling(window=14).mean()
avg_loss = loss.rolling(window=14).mean()
rs = avg_gain / avg_loss
df['rsi'] = 100 - (100 / (1 + rs))
# 计算OBV指标
df['obv'] = np.where(df['return'] > 0, df['volume'], -df['volume']).cumsum()
# 计算线性回归
X = np.array(df.index).reshape(-1, 1)
y = df['close'].values
reg = LinearRegression().fit(X, y)
df['trend'] = reg.predict(X)
# 绘制图表
plt.plot(df.index, df['close'], label='Close')
plt.plot(df.index, df['ma5'], label='MA5')
plt.plot(df.index, df['ma20'], label='MA20')
plt.fill_between(df.index, df['upper'], df['lower'], alpha=0.2, label='Bollinger Bands')
plt.plot(df.index, df['macd'], label='MACD')
plt.plot(df.index, df['signal'], label='Signal')
plt.plot(df.index, df['rsi'], label='RSI')
plt.plot(df.index, df['obv'], label='OBV')
plt.plot(df.index, df['trend'], label='Trend')
plt.legend()
plt.show()
```
这段代码可以读取股票数据,计算收益率、移动平均线、布林带、MACD指标、RSI指标、OBV指标和线性回归,并绘制图表展示这些指标的变化趋势。
阅读全文