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

如何用yfinance模块获取比特币当前市场价格?

解决yfinance获取比特币当前价格的问题

你当前代码里调用的open字段是当日开盘价,并非实时市场价格。yfinance中比特币的当前价格对应info字典里的currentPrice字段,这是平台返回的最新成交价格。

修改后的可用代码如下:

import yfinance as yF

BTC = yF.Ticker("BTC-GBP")
# 获取实时当前价格
current_price = BTC.info.get('currentPrice')
if current_price:
    print("Bitcoin Current : ", round(current_price, 0))
else:
    # 备选方案:若currentPrice字段缺失,用买价和卖价的平均值替代
    bid_price = BTC.info.get('bid')
    ask_price = BTC.info.get('ask')
    if bid_price and ask_price:
        current_price = (bid_price + ask_price) / 2
        print("Bitcoin Current (Bid/Ask Avg) : ", round(current_price, 0))
    else:
        print("无法获取当前价格")

print("        Day     : ", round(BTC.info['dayLow'], 0), "-", round(BTC.info['dayHigh'], 0))
print("        52 Week : ", round(BTC.info['fiftyTwoWeekLow'], 0), "-", round(BTC.info['fiftyTwoWeekHigh'], 0))

关键说明:

  • currentPrice:这是yfinance提供的最接近实时的比特币成交价格,优先使用该字段。
  • 用get()方法替代直接索引,是为了避免字段不存在时触发KeyError,提升代码稳定性。
  • 如果currentPrice因API数据延迟等原因无法获取,可使用bid(买盘价格)和ask(卖盘价格)的平均值作为替代,逻辑和你处理其他指数的方式一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 19:22:34