How to download monthly frequency stock closing price from yahoo finance using python?

Member

by elvis , in category: Technical Analysis , 3 months ago

How to download monthly frequency stock closing price from yahoo finance using python?

Facebook Twitter LinkedIn Whatsapp

2 answers

Member

by norberto , 3 months ago

@elvis 

To download the monthly frequency stock closing prices from Yahoo Finance using Python, you can use the pandas_datareader library. Here's an example code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import pandas_datareader.data as web

# Define the stock symbol and start/end dates
symbol = 'AAPL'
start_date = '2000-01-01'
end_date = '2022-01-01'

# Download the stock data from Yahoo Finance
# Specify 'mo' for monthly frequency
df = web.DataReader(symbol, 'yahoo', start_date, end_date, interval='mo')

# Select only the 'Close' column
df = df['Close']

# Print the downloaded data
print(df)


Make sure you have the pandas and pandas_datareader libraries installed in your Python environment. You can install them via pip:

1
pip install pandas pandas-datareader


Replace 'AAPL' with the desired stock symbol and '2000-01-01' and '2022-01-01' with your desired start and end dates.


The code will output a DataFrame containing the monthly closing prices for the specified stock symbol during the specified time period.

Member

by amparo , 5 days ago

@elvis 

The provided code is a great way to download the monthly closing prices of a stock from Yahoo Finance using Python. Just to add on, in case you encounter any SSL certificate errors, you can update the SSL module by using the following command:

1
pip install certifi


Additionally, Yahoo Finance sometimes changes its API endpoints, leading to intermittent issues with pandas_datareader. If you face any problems, you can consider using the yfinance library as an alternative. Here's how you can modify the code to use yfinance:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import yfinance as yf

# Define the stock symbol and start/end dates
symbol = 'AAPL'
start_date = '2000-01-01'
end_date = '2022-01-01'

# Download the stock data using yfinance
data = yf.download(symbol, start=start_date, end=end_date, interval='1mo')
df = data['Close']

# Print the downloaded data
print(df)


The yfinance library provides a straightforward way to fetch historical market data and is often updated to counter any API changes. Just like pandas_datareader, remember to install yfinance by running:

1
pip install yfinance


This should help you download monthly frequency stock closing prices from Yahoo Finance using Python with both the pandas_datareader and yfinance libraries.