用python实现股票预测的代码
时间: 2023-05-24 21:01:56 浏览: 114
以下是一个简单的用 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['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)
df.dropna(inplace=True)
# 创建新特征
df['HL_PCT'] = (df['High'] - df['Low']) / df['Close'] * 100.0
df['PCT_change'] = (df['Close'] - df['Open']) / df['Open'] * 100.0
# 准备数据
X = np.array(df.drop(['Close'], 1))
y = np.array(df['Close'])
# 划分数据集
split_index = int(0.8 * len(df))
X_train, X_test, y_train, y_test = X[:split_index], X[split_index:], y[:split_index], y[split_index:]
# 创建模型
model = LinearRegression()
model.fit(X_train, y_train)
# 测试模型
accuracy = model.score(X_test, y_test)
# 输出得分
print('Accuracy:', accuracy)
```
请注意,此代码仅仅是一个简单的股票预测模型,可能并不准确。
阅读全文