使用yfinance绘制公司股份数遇ValueError,如何用Numpy修复?
解决yfinance绘制股份数量时的ValueError问题
问题场景
用yfinance获取微软(MSFT)的股份数量并按日期绘图时,运行代码触发如下错误:
原代码
import yfinance as yf import matplotlib.pyplot as plt ticker_symbol = 'MSFT' stock = yf.Ticker(ticker_symbol) s = stock.get_shares_full() s = stock.get_shares_full(start="2023-01-01") print(s) # 输出示例: # 2023-01-04 00:00:00-05:00 7461940224 # 2023-01-06 00:00:00-05:00 7454470144 # ... # dtype: int64 dates=s.index shares=s.values plt.plot(dates, shares)
错误提示
ValueError: Multi-dimensional indexing (e.g. `obj[:, None]`) is no longer supported. Convert to a numpy array before indexing instead.
用Numpy解决的方案
问题出在yfinance返回的shares数据结构无法被matplotlib直接处理,转成numpy数组就能解决。修改后的完整代码如下:
import yfinance as yf import matplotlib.pyplot as plt import numpy as np ticker_symbol = 'MSFT' stock = yf.Ticker(ticker_symbol) # 直接一次获取指定起始日期的股份数据,不用重复调用 s = stock.get_shares_full(start="2023-01-01") dates = s.index # 把shares转换成numpy数组 shares = np.array(s.values) plt.plot(dates, shares) plt.title(f'{ticker_symbol} 2023年以来股份数量变化') plt.xlabel('日期') plt.ylabel('股份数量') plt.xticks(rotation=45) # 旋转日期标签避免重叠 plt.tight_layout() # 自动调整布局 plt.show()
核心修改点
- 新增导入
numpy库 - 用
np.array(s.values)将原数据转为numpy数组,规避多维索引的兼容问题 - 优化原代码:删除重复的
get_shares_full()调用,提升效率
内容的提问来源于stack exchange,提问作者mahmood
相关产品推荐
相关产品推荐

