You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用matplotlib绘制yfinance数据触发ValueError维度报错求助

问题原因分析

报错的核心是手动给返回的行情数据增加了多余的维度:

  • yfinance的Ticker.history()接口返回的本身就是二维Pandas DataFrame,行是时间维度、列是开盘/收盘/最高/最低/交易量等行情字段
  • 你代码里把返回结果套了一层[],变成了[DataFrame]的列表嵌套结构,导致传入plt.plot()时多了一维,触发维度不匹配的报错

另外还有两个影响绘图的逻辑问题:

  • plt.figure()声明的顺序错误,应该先创建画布,再往画布上绘图,否则你定义的画布尺寸和坐标轴标签不会生效
  • 直接传入整个DataFrame绘图会同时画7个行情字段的曲线,如果你只需要看价格走势,建议指定对应的列(比如常用的收盘价Close)
修正方案

按以下步骤调整代码即可正常绘图:

  1. 去掉hist赋值时多余的方括号,直接接收接口返回的DataFrame
  2. 调整画布创建顺序,指定要绘制的行情列
  3. 若需要绘制多个行情字段,单独指定对应列即可避免混乱

调整后的完整代码

import yfinance as yf
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

BTC_EUR = yf.Ticker("BTC-EUR")
# 去掉多余的方括号,直接接收返回的DataFrame
hist = BTC_EUR.history(period="max")
rec = BTC_EUR.recommendations
info = BTC_EUR.info
price = BTC_EUR.info['regularMarketPrice']
supply = BTC_EUR.info['circulatingSupply']
market_cap = price*supply
moskau_zeit = 1/price*100000000
fiftytwoweeks = BTC_EUR.info['fiftyTwoWeekLow']
price_since_fiftytwoweeks = (price/fiftytwoweeks-1)*100
day_low = BTC_EUR.info['dayLow']
day_high = BTC_EUR.info['dayHigh']

print(hist)
print(price)

if price < day_low:
  print(f"Buy! The price is at {price:,.2f} EUR/BTC")
  
if price > day_high:
 print(f"Dont buy now, too expensive! The price is at {price:,.2f} EUR/BTC")

if price > day_low and price < day_high:
 print(f"Wait, market isnt moving rn! The price is at {price:,.2f} EUR/BTC")
 
print(f"There are {supply:,.2f} BTC in circulation. This is {supply/21000000*100:,.2f}% of the aggregate supply.")
print(f"The market cap is {market_cap:,.2f} high")
print(f"The moskau time is {moskau_zeit:,.2f} SAT/EUR")
print(f"The price of BTC has risen by {price_since_fiftytwoweeks:,.2f}% since the 52 weeks-low of {fiftytwoweeks:,.2f} euros")

# 先创建画布,再绘图
plt.figure(figsize= (12,12))
# 指定绘制收盘价曲线,也可以换成你需要的其他列比如High、Low
plt.plot(hist['Close'])
plt.xlabel('Zeit')
plt.ylabel('Kurspreis')
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:18:05