如何用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
相关产品推荐
相关产品推荐

