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

如何修复异步获取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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:10:31