You need to enable JavaScript to run this app. Jupyter Notebook中yfinance股票预测Python代码运行报错如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Jupyter Notebook中yfinance股票预测Python代码运行报错如何解决?

Python股票预测程序运行报错修复方案

问题背景

今年3月编写的Python股票预测程序,当时在Jupyter Notebook中运行完全正常,现在重新运行出现报错,无法定位问题原因。

相关截图

  • 报错提示:报错提示
  • 正常运行效果:正常运行效果

当前报错的完整代码

import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime
import seaborn
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.linear_model import LinearRegression
pd.options.mode.chained_assignment = None  # default='warn'


df = yf.download("spy")
df.to_csv('spy.csv')
df = df[['Adj Close']]
plt.plot(df)

df['Adj Close'].plot(figsize=(15,6), color = 'g')
plt.legend(loc='upper left')
plt.show()


forecast = 70
df['Prediction'] = df[['Adj Close']].shift(-forecast)
X = np.array(df.drop(['Prediction'], 1))
X = preprocessing.scale(X)            
X_forecast = X[-forecast:]
X = X[:-forecast]
y = np.array(df['Prediction'])
y = y[:-forecast]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
clf = LinearRegression()
clf.fit(X_train, y_train)
confidence = clf.score(X_test, y_test)
confidence
forecast_predicted = clf.predict(X_forecast)
print(forecast_predicted)

plt.plot(X, y)

dates = pd.date_range(start="2021-05-21", end= "2021-06-19")
plt.plot(dates, forecast_predicted, color='b')
df['Adj Close'].plot(color='g')
plt.xlim(xmin = datetime.date(2020,5,1))
plt.xlim(xmax = datetime.date(2021,7,1))

历史正常运行的末尾代码片段

dates = pd.date_range(start="2021-03-16", end= "2021-04-14")
plt.plot(dates, forecast_predicted, color='b')
df['Adj Close'].plot(color='g')
plt.xlim(xmin = datetime.date(2020,3,1))
plt.xlim(xmax = datetime.date(2021,5,1))

报错原因

两个核心问题导致报错:

  1. 新版Pandas中drop方法不再支持直接传入位置参数代表轴方向,必须明确指定axis=1才可以删除列
  2. 代码写死了预测日期区间和x轴显示范围,每次重新运行yf.download获取的SPY数据会更新到最新日期,预测的70天区间对应实际日期已经发生变化,写死的日期长度和预测结果长度不匹配,触发维度不一致报错

修复后的代码

import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime
import seaborn
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.linear_model import LinearRegression
pd.options.mode.chained_assignment = None  # default='warn'


df = yf.download("spy")
df.to_csv('spy.csv')
df = df[['Adj Close']]
plt.plot(df)

df['Adj Close'].plot(figsize=(15,6), color = 'g')
plt.legend(loc='upper left')
plt.show()


forecast = 70
df['Prediction'] = df[['Adj Close']].shift(-forecast)
# 修复点1:明确指定axis=1适配新版Pandas语法
X = np.array(df.drop(['Prediction'], axis=1))
X = preprocessing.scale(X)            
X_forecast = X[-forecast:]
X = X[:-forecast]
y = np.array(df['Prediction'])
y = y[:-forecast]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
clf = LinearRegression()
clf.fit(X_train, y_train)
confidence = clf.score(X_test, y_test)
print("模型置信度:", confidence)
forecast_predicted = clf.predict(X_forecast)
print(forecast_predicted)

plt.figure(figsize=(15,6))
# 修复点2:动态生成预测日期,保证和预测结果长度匹配
last_date = df.index[-1]
dates = pd.date_range(start=last_date + pd.Timedelta(days=1), periods=forecast)
plt.plot(dates, forecast_predicted, color='b', label='预测价格')
df['Adj Close'].plot(color='g', label='实际调整收盘价')
# 修复点3:动态设置x轴范围,适配数据更新
plt.xlim(xmin = last_date - datetime.timedelta(days=365), xmax = dates[-1])
plt.legend(loc='upper left')
plt.show()

内容的提问来源于stack exchange,提问作者V N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 11:54:00