m0_74420115 2024-05-07 18:32 采纳率: 71.9%
浏览 14

python预测股票

修改这个代码,预测2004-2024年的股票价格,并且把2004-2024预测的股票的价格和实际的股票价格画到一张图上进行对比

修改这个代码,预测2004-2024年的股票价格,并且把2004-2024预测的股票的价格和实际的股票价格画到一张图上进行对比
import pandas as pd
def parse_date(date_string):
    return pd.Timestamp(date_string.replace('_', '-'))
df = pd.read_csv('D:/LSTMdata.csv', index_col='Date', parse_dates=True, date_parser=parse_date)
df.sort_index(inplace=True)
predict_count = int(len(df)*0.02)
df['label'] = df['Close'].shift(-predict_count)
X = df.drop(['label'],axis=1)
y = df['label'][:-predict_count]
from sklearn.preprocessing import StandardScaler
scale = StandardScaler()
scale.fit(X)
X = scale.transform(X)
X_lately = X[-predict_count:]
X = X[:-predict_count]
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(x_train, y_train)
model.score(x_test, y_test)
predict = model.predict(X_lately)
import numpy as np
df['predict'] = np.nan
import datetime
# print(df.index[-1])
last_date_st = df.index[-1].timestamp()
next_date_st = last_date_st + 86400

# print(next_date)

for i in predict:
    next_date = datetime.datetime.fromtimestamp(next_date_st)
    df.loc[next_date] = [np.nan for _ in range(len(df.columns)-1)] + [i]
    next_date_st +=  86400
import matplotlib.pyplot as plt
import matplotlib.style as style
style.use('ggplot')
df['Close'].plot()
df['predict'].plot()
plt.show()

  • 写回答

3条回答 默认 最新

  • GISer Liu 2024-05-08 03:00
    关注

    该回答引用自GPT-3.5,由博主GISer Liu编写:

    首先,我们需要修改代码以预测 2004 年至 2024 年的股票价格,并将预测结果与实际价格进行对比。以下是解决方案的详细步骤:

    1. 数据准备
    • 导入 pandas 库,读取股票数据。
    • 创建一个函数 parse_date 用于解析日期格式。
    • 使用 pd.read_csv 读取数据文件,设置 index_col='Date' 表示使用日期作为索引,并解析日期列。
    • 排序数据,以确保按日期顺序排列。
      python
      Copy code
      import pandas as pd
      def parse_date(date_string):
      return pd.Timestamp(date_string.replace('_', '-'))
      df = pd.read_csv('D:/LSTMdata.csv', index_col='Date', parse_dates=True, date_parser=parse_date)
      df.sort_index(inplace=True)
      
    1. 数据预处理
    • 创建一个新列 'label',其中包含未来预测的股票价格。
    • 分割特征和目标变量。
    • 使用 StandardScaler 对特征进行标准化。
      python
      Copy code
      predict_count = int(len(df) * 0.02)
      df['label'] = df['Close'].shift(-predict_count)
      X = df.drop(['label'], axis=1)
      y = df['label'][:-predict_count]
      from sklearn.preprocessing import StandardScaler
      scale = StandardScaler()
      scale.fit(X)
      X = scale.transform(X)
      X_lately = X[-predict_count:]
      X = X[:-predict_count]
      
    1. 模型训练
    • 划分训练集和测试集。
    • 使用线性回归模型进行训练。
      python
      Copy code
      from sklearn.model_selection import train_test_split
      x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
      from sklearn.linear_model import LinearRegression
      model = LinearRegression()
      model.fit(x_train, y_train)
      
    1. 进行预测
    • 预测未来股票价格,并将预测结果添加到 DataFrame 中。
      python
      Copy code
      predict = model.predict(X_lately)
      import numpy as np
      df['predict'] = np.nan
      import datetime
      last_date_st = df.index[-1].timestamp()
      next_date_st = last_date_st + 86400
      for i in predict:
      next_date = datetime.datetime.fromtimestamp(next_date_st)
      df.loc[next_date] = [np.nan for _ in range(len(df.columns)-1)] + [i]
      next_date_st += 86400
      
    1. 可视化对比
    • 使用 Matplotlib 将实际股票价格和预测股票价格绘制在同一张图上进行对比。
      python
      Copy code
      import matplotlib.pyplot as plt
      import matplotlib.style as style
      style.use('ggplot')
      df['Close'].plot(label='Actual Stock Price')
      df['predict'].plot(label='Predicted Stock Price')
      plt.legend()
      plt.show()
      
      通过这些步骤,我们就能够完成对股票价格的预测,并将预测结果与实际价格进行对比。

    如果该回答解决了您的问题,请采纳!如果没有,请私信联系或评论您的疑惑

    评论

报告相同问题?

问题事件

  • 创建了问题 5月7日