给我完整格式的代码
时间: 2023-08-06 17:16:45 浏览: 55
完整代码
5星 · 资源好评率100%
好的,以下是完整格式的代码:
```python
import pandas_datareader as pdr
import pandas as pd
import ta
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
# 下载股票历史数据
df = pdr.get_data_yahoo('AAPL', start='2010-01-01', end='2021-01-01')
df.to_csv('AAPL.csv')
# 加载数据
df = pd.read_csv('AAPL.csv', index_col='Date', parse_dates=['Date'])
# 计算特征
df['ma5'] = df['Adj Close'].rolling(5).mean()
df['ma10'] = df['Adj Close'].rolling(10).mean()
df['ma20'] = df['Adj Close'].rolling(20).mean()
df['ma50'] = df['Adj Close'].rolling(50).mean()
df['ma100'] = df['Adj Close'].rolling(100).mean()
df['ma200'] = df['Adj Close'].rolling(200).mean()
df['ewm12'] = df['Adj Close'].ewm(span=12, adjust=False).mean()
df['ewm26'] = df['Adj Close'].ewm(span=26, adjust=False).mean()
df['macd'] = df['ewm12'] - df['ewm26']
df['rsi14'] = ta.momentum.RSIIndicator(df['Adj Close'], window=14).rsi()
# 准备数据
train = df.loc[df.index < '2020-01-01']
test = df.loc[df.index >= '2020-01-01']
# 训练模型
features = ['ma5', 'ma20', 'ma50', 'ma100', 'ma200', 'rsi14']
label = 'label'
X_train = train[features]
y_train = train[label]
X_test = test[features]
y_test = test[label]
model = LogisticRegression()
model.fit(X_train, y_train)
# 测试模型
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
请注意,这段代码中涉及到的股票数据只是一个示例,你可以根据自己的需求修改相应的代码。此外,这个示例仅供学习和演示目的,不应该用于实际的投资决策。
阅读全文