我正在使用Python中的雅虎金融库和请求库。当我尝试调用几个月或几年的历史数据(例如“1mo”或“1y”)时,我收到错误 422。
我尝试调用另一只股票和不同的月份周期(例如 3 个月),但结果相同。这是我使用的代码,它给了我错误代码 422:
import requests
def fetch_yahoo_finance_data(symbol, interval='1m', range_='1mo'):
url
=f"https://query1.finance.yahoo.com/v8/finance/chart/{symbol}?
interval={interval}&range={range_}"
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
return data
else:
print(f"Failed to fetch data. Status
Code{response.status_code}")
return None
data = fetch_yahoo_finance_data('BMW.DE', "1m", "1mo")
我使用雅虎财务模块
yfinance
来实现相同的目的(而不是使用问题中尝试的 URL 方法,该方法具有未定义的 headers
变量)。
这是我使用的代码:
import yfinance as yf
from datetime import datetime, timedelta
# Define the ticker symbol for BMW. Use "BMW.DE" for the Frankfurt Stock Exchange.
ticker_symbol = "BMW.DE"
# Create a ticker object
bmw_ticker = yf.Ticker(ticker_symbol)
# Calculate the date 6 months ago from today
six_months_ago = datetime.now() - timedelta(days=6*30) # Approximation of 6 months
# Fetch the historical data for BMW for the last 6 months
bmw_data = bmw_ticker.history(
start=six_months_ago.strftime('%Y-%m-%d'),
end=datetime.now().strftime('%Y-%m-%d'))
# Display the closing prices
print(bmw_data['Close'])
结果如下所示:
Date
2023-07-18 00:00:00+02:00 107.099998
2023-07-19 00:00:00+02:00 107.199997
2023-07-20 00:00:00+02:00 107.680000
2023-07-21 00:00:00+02:00 107.580002
2023-07-24 00:00:00+02:00 108.599998
...
2024-01-08 00:00:00+01:00 101.199997
2024-01-09 00:00:00+01:00 100.820000
2024-01-10 00:00:00+01:00 99.900002
2024-01-11 00:00:00+01:00 98.459999
2024-01-12 00:00:00+01:00 96.849998
Name: Close, Length: 125, dtype: float64