Empyz
Empyz

Reputation: 59

How do I return the the historical data for the past X years until current day for a stock using yahoo finance data?

I'm trying to retrieve the historical data for the stock AAPL, but the below code has me specify between certain dates. How can I make it so that it automatically pulls the data for the past 5 years until current date instead?

import time
import datetime
import pandas as pd

ticker = 'AAPL'
period1 = int(time.mktime(datetime.datetime(2022, 1, 1, 23, 59).timetuple()))
period2 = int(time.mktime(datetime.datetime(2022, 2, 28, 23, 59).timetuple()))
interval = '1d' # 1wk, 1m

query_string = f'https://query1.finance.yahoo.com/v7/finance/download/{ticker}?period1={period1}&period2={period2}&interval={interval}&events=history&includeAdjustedClose=true'

df = pd.read_csv(query_string)
print(df)
df.to_csv('AAPL.csv')

Upvotes: 0

Views: 2301

Answers (1)

MD Mushfirat Mohaimin
MD Mushfirat Mohaimin

Reputation: 2066

You can use yfinance to retrieve the data,
install using pip:

pip install yfinance

Use this code to retrieve the past 5 years of historical data of 'AAPL',

import yfinance as yf

df = yf.download('AAPL', period='5y')

You can also use yf.Ticker to do it:

ticker = yf.Ticker('AAPL')
df = ticker.history(period="5y")

Upvotes: 2

Related Questions