1. Get Stock Data for Specific Dates
You can fetch stock data for specific start and end dates by passing them directly to the yf.download()
function.
import yfinance as yf
# Specify stock symbol and dates
stock_symbol = 'AAPL'
start_date = '2023-01-01'
end_date = '2023-09-01'
# Download stock data for specific dates
stock_data = yf.download(stock_symbol, start=start_date, end=end_date)
# Display the first few rows of the data
print(stock_data.head())
In this case, it retrieves Apple’s stock data from January 1, 2023, to September 1, 2023.
2. Get Stock Data for a Relative Time Period (e.g., 1 Year)
If you want to fetch data for a relative period (such as the last year), you can use yf.Ticker
and specify the period (like 1y
for 1 year).
import yfinance as yf
# Define the stock symbol
stock_symbol = 'AAPL'
# Get stock data for the last 1 year
stock = yf.Ticker(stock_symbol)
stock_data = stock.history(period='1y') # '1y' means one year
# Display the first few rows of the data
print(stock_data.head())
The period
argument in the history()
method allows you to specify relative time frames like:
'1d'
: 1 day'5d'
: 5 days'1mo'
: 1 month'6mo'
: 6 months'1y'
: 1 year'5y'
: 5 years'max'
: All available data
3. Get Data For A Custom Period (e.g., Last 30 Days From Current Day)
You can also specify custom periods like the last 30 days or any other range.
import yfinance as yf
from datetime import datetime, timedelta
# Define the stock symbol
stock_symbol = 'AAPL'
# Get today's date and calculate the date 30 days ago
end_date = datetime.now()
start_date = end_date - timedelta(days=30)
# Download stock data for the last 30 days
stock_data = yf.download(stock_symbol, start=start_date, end=end_date)
# Display the first few rows of the data
print(stock_data.head())
4. Get Stock Data For Specific Interval (e.g., 1minute, 30 minutes)
import yfinance as yf
from datetime import datetime, timedelta
# Define the stock symbol
stock_symbol = 'AAPL'
# Get today's date and calculate the date 30 days ago
end_date = datetime.now()
start_date = end_date - timedelta(days=30)
# Download stock data for the last 30 days
SYMBOL = "QQQ"
STOCK = yf.Ticker(SYMBOL)
stock_data = STOCK.history(start=start_date,end=end_date,interval='30m')
# Display the first few rows of the data
print(stock_data.head())
Learn more yFinnce Get (Download) Stock Data Using Python