如何修复异步获取yfinance每日数据却返回周数据的问题?
修复异步获取Yahoo金融每日数据的问题
你的代码里设置了interval: '1d'却只能拿到周数据,核心原因是Yahoo Finance的API在使用range: 'max'时,对于加密货币这类资产会默认调整返回的时间粒度。解决方法是用period1和period2参数替代range,明确指定时间范围,同时补充必要参数确保返回每日数据。
修改后的完整代码如下:
import aiohttp import asyncio import pandas as pd from io import StringIO import time ticker = 'BTC-USD' # 移除URL末尾多余的问号,aiohttp会自动处理参数拼接 url = f'https://query1.finance.yahoo.com/v7/finance/download/{ticker}' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.57' } params = { # period1设为0表示从最早可获取的时间开始,period2设为当前时间戳 'period1': 0, 'period2': int(time.time()), 'interval': '1d', 'events': 'history', 'includeAdjustedClose': 'true' } async def fetch(session, url, params, headers): async with session.get(url, params=params, headers=headers) as response: return await response.text() async def get_data(): async with aiohttp.ClientSession() as session: response_text = await fetch(session, url, params, headers) df = pd.read_csv(StringIO(response_text)) # 可检查数据的时间范围与行数 print("数据时间范围:", df['Date'].iloc[0], "到", df['Date'].iloc[-1]) print("数据行数:", len(df)) print(df.head()) asyncio.run(get_data())
关键修改点:
- 移除URL末尾的多余问号,避免参数拼接时出现异常
- 用
period1(起始时间戳,0代表最早可获取时间)和period2(当前时间戳)替代range: 'max',强制API返回指定时间范围内的全量数据 - 添加
includeAdjustedClose: 'true'参数,确保返回调整后的收盘价,与yf.download默认行为一致
内容的提问来源于stack exchange,提问作者RANVER
相关产品推荐
相关产品推荐

