Why is Yfinance library for months not working?

192 Views Asked by At

I am using the Yahoo finance library and the requests library in python. When I try to call historic data for ranges of months or years, like "1mo" or "1y" I get the error 422.

I tried to call another stock and different month periods like 3 months, but it is the same result. This is the code I use, which gives me the error code 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") 
1

There are 1 best solutions below

0
D.L On

i use the yahoo finance module yfinance to achieve the same (as opposed to using the URL method attmepted in the question which had an undefined headers variable).

this is the code that i use:

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'])

And the result look like this:

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