pandas 如何从yfinance异步获取每日数据?

64jmpszr  于 2023-03-06  发布在  其他
关注(0)|答案(1)|浏览(151)

以前我只是使用www.example.com来获取数据,但是现在我必须异步地进行。yf.download for data, but now i have to do it asynchronously.
我有这个密码

import aiohttp
import asyncio
import pandas as pd
from io import StringIO

ticker = 'BTC-USD'
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 = {
    'range': 'max',
    'interval': '1d',  # change interval to '1d' for daily data
    'events': 'history'
}

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 = await fetch(session, url, params, headers)
        df = pd.read_csv(StringIO(response))
        print(df)

asyncio.run(get_data())

但是它只能得到每周的数据。我怎么能修复它呢?

laawzig2

laawzig21#

尝试将参数更改为period1/period2

import time
import aiohttp
import asyncio
import pandas as pd
from io import StringIO

ticker = 'BTC-USD'
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': int(time.time()),
    'interval': '1d',  # change interval to '1d' for daily data
    'events': 'history'
}

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 = await fetch(session, url, params, headers)
        df = pd.read_csv(StringIO(response))
        print(df)

asyncio.run(get_data())

图纸:

Date          Open          High           Low         Close     Adj Close        Volume
0     2014-09-17    465.864014    468.174011    452.421997    457.334015    457.334015      21056800
1     2014-09-18    456.859985    456.859985    413.104004    424.440002    424.440002      34483200
2     2014-09-19    424.102997    427.834991    384.532013    394.795990    394.795990      37919700
3     2014-09-20    394.673004    423.295990    389.882996    408.903992    408.903992      36863600

...

3086  2023-02-28  23521.837891  23585.384766  23077.650391  23147.353516  23147.353516   20535363434
3087  2023-03-01  23150.929688  23880.632813  23088.626953  23646.550781  23646.550781   24662841200
3088  2023-03-02  23641.416016  23739.138672  23249.398438  23487.048828  23487.048828   20472512512

相关问题