Pandas time series: Adjust stock price after paying dividends or splitting – Example

Introduction

Pandas, the beloved Python library for data manipulation and analysis, offers versatile tools to handle time series data. Financial time series, such as stock prices, often undergo adjustments due to dividends payout and stock splits. This tutorial will guide you through adjusting stock prices using Pandas, ensuring your historical data reflects accurate market values for analysis.

Stock prices on public markets are affected by two main events – dividends payout and stock splits or reverse splits. Dividends are profits shared with shareholders, reducing the company’s share price by a similar amount on the ex-dividend date. Stock splits adjust the share price by increasing the quantity of shares, making the stock more liquid and affordable without changing the company’s market capitalization. To perform accurate historical price analysis, these adjustments must be accounted for.

Getting Started

First, ensure you have Pandas installed:

``pip install pandas``

Then, import Pandas and other necessary libraries:

``````import pandas as pd
import numpy as np``````

Fetching Stock Data

For this example, let’s work with fictional stock data. However, you can fetch real stock price data from sources like Yahoo Finance using `pandas_datareader`.

``````from pandas_datareader import data as pdr
# Fetching Apple Inc. stock data
aapl = pdr.get_data_yahoo('AAPL', start='2010-01-01', end='2023-01-01')``````

With the data fetched, let’s simulate dividend payouts and stock splits.

Simulating Dividends and Splits

Let’s assume our fictional company pays a \$1 dividend per share annually and had a 2-for-1 stock split in 2015. For simplicity, dividends are paid out at the end of the year.

``````# Adding simulated dividend payouts
dividends = pd.Series([1.0 for _ in range(len(aapl.index))], index=aapl.index, name='Dividends')
# Simulate a stock split in 2015
splits = pd.Series([2.0 if x.year == 2015 else 1.0 for x in aapl.index], index=aapl.index, name='Splits')

To adjust the closing stock price for dividends, we reduce the stock price by the dividend amount on the ex-dividend date.

``````# Adjusting closing stock prices for dividends

``````# Adjusting for a 2-for-1 stock split