Sling Academy
Home/Python/Fetching Historical Stock Prices with pandas-datareader

Fetching Historical Stock Prices with pandas-datareader

Last updated: December 22, 2024

Fetching historical stock prices is a common task for data analysts and financial analysts. With the pandas-datareader library, this process becomes relatively straightforward in Python. This article will walk you through the steps required to use pandas-datareader to access historical stock data.

Prerequisites

Before you begin, ensure you have Python installed on your computer. Additionally, you will need to install the pandas and pandas-datareader libraries. You can install these libraries using pip:

pip install pandas pandas-datareader

Import the Required Libraries

First, let’s import the necessary libraries. We'll need pandas to manipulate the data and pandas_datareader to fetch it.

import pandas as pd
import pandas_datareader.data as web
from datetime import datetime

Set Your Time Frame

Define the start and end dates for the period you are interested in. For this, the datetime library is convenient. Here's an example:

start = datetime(2020, 1, 1)
end = datetime(2023, 10, 1)

Fetch Data

With your dates defined, you can now fetch the stock data using the DataReader. The yahoo option allows you to access stock price data:

ticker_symbol = 'AAPL'  # Example with Apple Inc.
data = web.DataReader(ticker_symbol, 'yahoo', start, end)

This will give you a DataFrame object containing the stock data, which includes columns like 'Open', 'High', 'Low', 'Close', 'Volume', and 'Adj Close'.

Inspect the Data

Let's take a quick look at the first few rows of the dataset to understand the information structure:

print(data.head())

You should see an output like this:


                 High        Low       Open      Close  Volume  Adj Close
Date
2020-01-02  75.150002  73.797501  74.060000  75.087502  33870100  74.644424
2020-01-03  75.144997  74.125000  74.287498  74.357498  36580700  73.918152

Data Manipulation and Visualization

With pandas, it's easy to manipulate and plot time-series data. Here’s how you can plot the closing prices over time:

import matplotlib.pyplot as plt
data['Close'].plot(title="Closing Price Trend", figsize=(10,6))
plt.xlabel('Date')
plt.ylabel('Close Price USD ($)')
plt.show()

This code will generate a line plot of Apple’s closing stock prices over the specified period.

Error Handling

Fetching data over the internet can often lead to request errors such as connectivity issues. It's advisable to implement basic error handling:

try:
    data = web.DataReader(ticker_symbol, 'yahoo', start, end)
except Exception as e:
    print(f"An error occurred: {e}")

Conclusion

Using pandas-datareader, you can efficiently access and analyze historical stock data for any company with minimal coding. This can be extremely valuable for conducting financial analyses, building predictive models, or creating data visualizations. With the foundation laid in this article, you're now equipped to extend this framework to other financial instruments and additional sources of financial data available through different pandas-datareader libraries.

Next Article: Combining pandas-datareader with pandas for In-Depth Data Analysis

Previous Article: Common pandas-datareader Errors: How to Debug and Resolve

Series: Algorithmic trading with Python

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots