使用函数history提取股票信息时出现“AttributeError: 'Index' object has no attribute 'tz_localize'”

问题描述 投票:0回答:2

我正在尝试提取特斯拉股票的信息,但是,我在编码时总是遇到错误。这是到目前为止的代码:

import plotly.graph_objects as go
import yfinance as yf
import pandas as pd
import requests

from bs4 import BeautifulSoup
from plotly.subplots import make_subplots

def make_graph(stock_data, revenue_data, stock):

    fig = make_subplots(rows=2, cols=1, shared_xaxes=True, subplot_titles=("Historical Share Price", "Historical Revenue"), vertical_spacing = .3)
    stock_data_specific = stock_data[stock_data.Date <= '2021--06-14']
    revenue_data_specific = revenue_data[revenue_data.Date <= '2021-04-30']
    fig.add_trace(go.Scatter(x=pd.to_datetime(stock_data_specific.Date, infer_datetime_format=True), y=stock_data_specific.Close.astype("float"), name="Share Price"), row=1, col=1)
    fig.add_trace(go.Scatter(x=pd.to_datetime(revenue_data_specific.Date, infer_datetime_format=True), y=revenue_data_specific.Revenue.astype("float"), name="Revenue"), row=2, col=1)
    fig.update_xaxes(title_text="Date", row=1, col=1)
    fig.update_xaxes(title_text="Date", row=2, col=1)
    fig.update_yaxes(title_text="Price ($US)", row=1, col=1)
    fig.update_yaxes(title_text="Revenue ($US Millions)", row=2, col=1)
    fig.update_layout(showlegend=False,
    height= 900,
    title= stock,
    xaxis_rangeslider_visible=True)
    fig.show()

Tesla= yf.Ticker('TSLA')
tesla_database= Tesla.history(period= "max")

在 tesla_database 部分出现以下错误:

Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    tesla_database= Tesla.history(period= "max")
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/yfinance/base.py", line 295, in history
    df.index = df.index.tz_localize("UTC").tz_convert(
AttributeError: 'Index' object has no attribute 'tz_localize'

我该如何解决这个问题?根据 Coursera 中的 IBM Watson 课程,这是正确的答案,但我总是收到此错误。请问有人可以纠正吗?

python data-science ibm-cloud watson-studio
2个回答
0
投票

我对 pandas 1.4.1 也有同样的问题,对我来说,恢复到以前的 pandas 版本解决了问题:

在命令行上尝试一下:

pip install pandas==1.2.2

从 Jupyter Board 尝试这个:

!pip install pandas==1.2.2

0
投票

仍然显示相同的错误,请分享任何其他解决方案

© www.soinside.com 2019 - 2024. All rights reserved.