Analyzing Dividend Cuts with Python and Deep Learning

Learn how to leverage Python and deep learning to analyze dividend cuts, calculate key financial metrics, and uncover advanced insights for strategic investment decisions.

6 min readMay 7, 2024

In this article, we’ll thoroughly explore dividend data analysis. We’ll look at the different aspects of dividend data, process them, and calculate key metrics needed for effective dividend analysis using Python and deep learning.

Python’s versatile libraries and frameworks facilitate intricate financial analyses. Deep learning, a branch of machine learning, further enhances these capabilities by identifying patterns within large datasets that human analysts might overlook. These patterns can help forecast future dividend trends, providing a valuable advantage in trading strategies.

A central part of our analysis is EODHD APIs. This API delivers comprehensive financial data, including extensive dividend histories crucial for our study. By blending Python’s analytical capabilities with deep learning algorithms and the real-time financial data from the EODHD APIs, we can extract valuable insights from dividend data, empowering traders to make more informed, data-driven decisions.

In this article, we’ll explore how to effectively harness these tools to enhance trading strategies through advanced dividend analysis. Our goal is to provide deeper insights into dividend trends, giving you a significant edge in decision-making.

Configuring Python and EODHD API for Dividend Data Analysis

To begin, it’s crucial to set up Python properly for financial analysis. Make sure you install key libraries like Pandas, NumPy, and Matplotlib to manipulate and visualize financial data. Additionally, integrating the EODHD API provides access to comprehensive financial information vital for dividend analysis.

Here’s a basic guide to start working with the EODHD API in Python:

1. Creating a Python Virtual Environment:

- Creating a virtual environment isolates your project’s dependencies.

- Run the following commands:

python3 -m venv myenv


source myenv/bin/activate.

Replace “myenv” with your desired environment name. You can skip this step if you prefer to use your existing environment.

2. Installing the EODHD API Library:

- To access live and historical stock data, install the EODHD library. It offers additional features that can aid in your analysis.

- Use pip to install:

pip install eodhd -U.

This ensures you have the latest version.

3. Installing Additional Libraries:

  • Install other essential libraries like NumPy, Pandas, and Matplotlib for data manipulation and visualization:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from eodhd import APIClient
import requests

With these steps, you’ll be equipped with the necessary tools to perform advanced dividend data analysis using Python and the EODHD API.

4. Setting Up the EODHD API Client

Now, let’s configure the EODHD API to kick off our dividend analysis. Begin by initializing the client with your API key, which you can obtain from the EODHD API access page:

api_key = "Your_API_Key"
base_url = ''

5. Fetching Historical Dividend Data

To retrieve the dividend data for a particular stock, we’ll use a function that queries the appropriate endpoint. For this example, we will analyze the dividend data for Nvidia (NVDA).

# Function to fetch dividend data
def fetch_dividend_data(symbol):
endpoint = f"{base_url}/div/{symbol}"
params = {
'api_token': api_key,
'fmt': 'json'
response = requests.get(endpoint, params=params)
if response.status_code == 200:
return response.json()
return None

stock_symbol = 'NVDA'

dividend_data = fetch_dividend_data(stock_symbol)
df_nvda = pd.DataFrame(dividend_data)

After running the above code, you will have a Pandas DataFrame containing Nvidia’s dividend data. Now, let’s see how this data looks for further analysis.

6. Data Preparation and Visualization

Now, let’s enhance the dataset by adding more features like the year and performing some data processing. After that, we’ll create a visualization to illustrate how Nvidia’s dividends have fluctuated since 2012.

df_nvda['date'] = pd.to_datetime(df_nvda['date'])
df_nvda['paymentDate'] = pd.to_datetime(df_nvda['paymentDate'])
df_nvda.sort_values('date', inplace=True)

df_nvda['year'] = df_nvda['date'].dt.year
df['dividend_change'] = df.groupby('year')['value'].transform(lambda x: x.pct_change())

plt.plot(df_nvda['date'], df_nvda['dividend'], marker='o', color='b')
plt.ylabel('Dividend Value')
plt.title('Quarterly Dividend Trend for NVDA')

Mathematical Foundations of Dividend Analysis

A thorough analysis of dividends requires quantifiable metrics to understand a company’s policies and stability. These metrics are essential for investors aiming to gauge and forecast dividend distributions.

1. Dividend Yield

The dividend yield shows how much a company pays out in dividends annually compared to its share price, providing an indication of the income generated by an investment.

Mathematical Formula:

2. Payout Ratio

The payout ratio compares dividends paid to net income, revealing how much profit is returned to shareholders versus how much is reinvested.

Mathematical Formula:

3. Dividend Growth Rate

This rate measures the annual percentage growth of a company’s dividend, indicating its growth trend.

Mathematical Formula:

4. Python Implementation

Using the EODHD API, we can compute these metrics as follows:

def fetch_stock_price(symbol, api_token):
api = APIClient(api_token)
data = api.get_historical_data(symbol=symbol, interval="d", iso8601_start="2012-01-01")
return data

stock_prices = fetch_stock_price('NVDA', api_key)
df_prices = pd.DataFrame(stock_prices)

df_merged = pd.merge_asof(df.sort_values('date'), df_prices.sort_values('date'), on='date')
df_merged['dividend_yield'] = df_merged['value'] / df_merged['close']

# Function to fetch annual earnings (net income) data
def fetch_annual_earnings(symbol, api_token):
income_statement_endpoint = f"{base_url}/fundamentals/{symbol}"
params = {
'api_token': api_token,
'fmt': 'json'
response = requests.get(income_statement_endpoint, params=params)
if response.status_code == 200:
# Extracting the annual income statement data
income_data = response.json()['Financials']['Income_Statement']['yearly']
return {year: data['netIncome'] for year, data in income_data.items()}
return None

net_income_data = fetch_annual_earnings('NVDA', api_key)
net_income_data = {int(key.split("-")[0]):int(float(value)) for key, value in net_income_data.items() if int(key.split("-")[0]) >= 2012}
# Calculating the total dividends paid annually
annual_dividends = df.groupby('year')['value'].sum()

# Calculating the payout ratio
payout_ratios = {}
for year, dividends in annual_dividends.items():
if year in net_income_data:
payout_ratios[year] = dividends / net_income_data[year]

dividend_growth_rates = df['dividend_change'].dropna()
average_dividend_growth_rate = dividend_growth_rates.mean()

These Python snippets help calculate key metrics like dividend yield, payout ratio, and dividend growth rate, offering valuable insights for robust dividend analysis.

In the end, we’ve gathered all the essential metrics that provide a solid foundation for deeper analysis. By combining these insights with advanced machine learning techniques, we can uncover hidden patterns and better predict future dividend trends, helping investors make well-informed, strategic decisions.

Exploring Future Possibilities in Dividend Analysis

After thoroughly calculating key financial metrics like dividend yield, payout ratio, and dividend growth rate, we’ve established a strong basis for advanced dividend analysis.

With these foundational metrics, we can conduct various types of analyses, such as:

1. Trend Analysis and Forecasting: Evaluate historical patterns and predict future dividend behavior, potentially using machine learning and deep learning models.

2. Comparative Analysis: Benchmark performance against industry standards or competitors to understand a company’s relative standing.

3. Dividend Sustainability Studies: Assess the long-term sustainability of a company’s dividend policy based on payout ratios and financial stability.

4. Risk Assessment: Identify potential risks of dividend cuts or inconsistencies and uncover their root causes.

5. Portfolio Optimization: Use these insights to inform investment strategies and create a dividend-focused portfolio aligned with specific goals.

The original article was published in the EODHD Academy by Pranjal Saxena.

In our upcoming articles, we’ll dive deeper into these analyses using Python programming, financial data analysis, and deep learning techniques.

Please note that this article is for informational purposes only and should not be taken as financial advice. We do not bear responsibility for any trading decisions made based on the content of this article. Readers are advised to conduct their research or consult with a qualified financial professional before making any investment decisions.

For those eager to delve deeper into such insightful articles and broaden their understanding of different strategies in financial markets, we invite you to follow our account and subscribe for email notifications.

Stay tuned for more valuable articles that aim to enhance your data science skills and market analysis capabilities.



EODHD APIs — stock market fundamental and historical prices API for stocks, ETFs, mutual funds and bonds all over the world.