How to download stock price data with python?

Member

by stuart , in category: Technical Analysis , 4 months ago

How to download stock price data with python?

Facebook Twitter LinkedIn Whatsapp

2 answers

by reba.quigley , 4 months ago

@stuart 

To download stock price data using Python, you can utilize several libraries. The most popular libraries for this task are pandas-datareader and yfinance. Here's an example using pandas-datareader:

  1. Install the necessary libraries by running the following command in your Python environment:
1
pip install pandas-datareader


  1. Import the required libraries:
1
import pandas_datareader as pdr


  1. Set the start and end dates for the data you want to download:
1
2
start_date = 'YYYY-MM-DD'
end_date = 'YYYY-MM-DD'


  1. Use pdr to download the stock data from Yahoo Finance (or other available sources) and store it in a pandas DataFrame:
1
data = pdr.get_data_yahoo('TICKER_SYMBOL', start=start_date, end=end_date)


Replace TICKER_SYMBOL with the stock's ticker symbol (e.g., "AAPL" for Apple).

  1. Print the downloaded data:
1
print(data)


Here's a complete example to download stock price data for Apple (AAPL) from Yahoo Finance for the past year:

1
2
3
4
5
6
7
import pandas_datareader as pdr

start_date = '2021-01-01'
end_date = '2021-12-31'

data = pdr.get_data_yahoo('AAPL', start=start_date, end=end_date)
print(data)


Make sure to adjust the ticker symbol and date range according to your requirements.

by francisco , a month ago

@stuart 

Alternatively, you can also use the yfinance library to download stock price data in Python. Here's how you can do it:


Install the yfinance library using pip:

1
pip install yfinance


Import the required libraries:

1
import yfinance as yf


Set the start and end dates for the data you want to download:

1
2
start_date = 'YYYY-MM-DD'
end_date = 'YYYY-MM-DD'


Download the stock data using yfinance and store it in a pandas DataFrame:

1
data = yf.download('TICKER_SYMBOL', start=start_date, end=end_date)


Replace TICKER_SYMBOL with the stock's ticker symbol.


Print the downloaded data:

1
print(data)


Here's a complete example to download stock price data for Apple (AAPL) using yfinance:

1
2
3
4
5
6
7
import yfinance as yf

start_date = '2021-01-01'
end_date = '2021-12-31'

data = yf.download('AAPL', start=start_date, end=end_date)
print(data)


You can adjust the ticker symbol and date range as needed for the stock you want to retrieve data for.