Financedevil
  • Investments
    • Precious Metals
  • Market activity
  • Personal Finance
    • Banking
    • Stocks
    • Crypto
    • Credit Cards
    • Loan
    • Taxes
  • Finance Tips
  • Insurance
  • Real Estate
  • Calculators
    • Additional Car Loan Payment
    • Car Loan Calculator
    • Mortgage Calculator
    • Rule of 72
    • Compound Interest
Quick Links
  • About Us
  • Contact
  • Disclaimer
  • Editorial Policy
  • Privacy Policy
  • Terms and Conditions
Networks
  • Editorial Policy
  • Car Loan Calculator
  • Mortgage Calculator
  • Rule of 72
Font ResizerAa
FinancedevilFinancedevil
  • Personal Finance
  • Stocks
  • Real Estate
  • Calculators
Search
  • Home
  • Investments
    • Standard and Poor’s 500
    • Dow Jones Industrial Average
    • Stock Quotes and Symbol Lookup
  • Finance Calculators
    • Additional Car Loan Payment
    • Car Loan Calculator
    • Compound Interest
    • Mortgage Calculator
    • Rule of 72
  • Real Estate
  • Market activity
    • Stocks
  • Personal Finance
    • Banking
    • Credit Cards
    • Finance Tips
    • Insurance
    • Taxes

Popular Posts

Insurance

General Liability Insurance

Tax Free Municipal Bonds
Investments

Tax-Exempt Municipal Bond

Growth Stock
Investments

Growth Stock

Finance Calculators

Finance Devil has created several calculators to help an investor reach his or her financial goals. If you have a question or suggestion for a new calculator, send us an email and we will build a new calculator and display the formula used.
Calculators
Follow US
Copyright © 2023 Financedevil. All rights reserved. A Digitalnations company.
Finance Tips

How to Track and Analyze Politicians Stock Trades

Abraham Nnanna
By Abraham Nnanna
Last updated: May 8, 2025
6 Min Read
Share

Introduction

How to Track and Analyze Politicians Stock Trades

For the past several months, I’ve been scraping data on stock trading by U.S. congressmen and creating visualizations showing weekly net stock purchases by senators alongside the market. As interest has grown in trading off this data, I want to provide a tutorial on how to get the data into Python and perform basic analysis.

Contents
IntroductionInstalling PythonGetting the DataBacktesting Trading StrategiesPredicting Trades with Machine LearningAnalyzing Trading Performance

Installing Python

For those new to the language, here is a tutorial on setting up Python.

Getting the Data

You can obtain data on trading by congressmen using the quiverquant package in Python. To install the package, run pip install quiverquant in your terminal. You’ll need to sign up for Quiver’s API to get a token to access the data.

Once you have your token, fetch data on trading by importing the Quiverquant package and connecting to the Quiver client.

{import quiverquant

# Replace <TOKEN> with your personal token

quiver = quiverquant.quiver(“<TOKEN>”)

df = quiver.congress_trading(“David Perdue”, True)

df.head(10)}

(embed code)

READ ALSO: Tips for Finding the Best Stocks to Day Trade

Basic Analysis

Here’s an example of some simple analysis you can do using the data. Note that this chunk of code requires that you pip install plotly.express.

Python

{import plotly.express as px

# Filter dataframe to purchases

dfBought = df[df[“Transaction”]==”Purchase”]

# Count how many times each stock was bought. Take the top 5 most bought.

dfStock = dfBought.groupby(“Ticker”).count().reset_index().sort_values(“Amount”, ascending=False).head(5)

# Graph

fig = px.bar(dfStock, x=’Ticker’, y=’Amount’, text=’Amount’)

fig.update_traces(marker_color=”rgb(218, 253, 214)”)

fig.update_layout(title=’Most Popular Stocks’, titlefont=dict(color=’white’), plot_bgcolor=’rgb(32,36,44)’, paper_bgcolor=’rgb(32,36,44)’)

fig.update_xaxes(title_text=’Stock’, color=’white’, showgrid=False)

fig.update_yaxes(title_text=’Transactions’, color=’white’, showgrid=True, gridwidth=1, gridcolor=”white”)

fig.show()}

(embed code)

Advanced Analysis

In addition to basic summary statistics and graphs, more advanced analysis can provide further insights into politicians’ trading strategies and performance.

Backtesting Trading Strategies

One approach is to backtest whether mimicking politicians’ trades would have been profitable. For example:

{# Filter to only purchases

df_buys = df[df[‘Transaction’] == ‘Purchase’]

# Go long stocks that were purchased, short stocks that were sold

portfolio = []

for _, row in df_buys.iterrows():

 if row [‘Ticker’] i not in the portfolio:

 portfolio.append(row[‘Ticker’]) 

 else:

 portfolio.remove(row[‘Ticker’])

# Calculate daily portfolio returns 

returns = []

for date, tickers in portfolio. groupby(df_buys[‘Disclosure Date’]): 

 weights = np.ones(len(tickers)) / len(tickers)

 returns.append(np.dot(weights, get_daily_returns(tickers, date)))

# Analyze performance vs benchmark

excess_returns = np.subtract(returns, get_benchmark_returns())

print(analyze_alpha_beta(excess_returns))}

(embed code)

This simulates a strategy of taking long stocks that politicians purchased and shorting those they sold. The output analyzes whether this strategy generated a significant alpha (outperformance) over the benchmark.

READ ALSO: 10 of the Best Stocks for Options Trading in 2024

Predicting Trades with Machine Learning

Machine learning algorithms can also be used to predict future trading activity:

{# Extract features like past returns, sectors, market cap

X = extract_features(df) 

# Target variable is whether stock was purchased 

y = df[‘Transaction’] == ‘Purchase’

# Train classification model

model = LogisticRegression()

model.fit(X, y)

# Make predictions on new data

predictions = model.predict(new_data)}

(embed code)

Here, a logistic regression model is trained to predict whether a politician will purchase a stock based on its characteristics. This model can then be used to generate trade recommendations.

Analyzing Trading Performance

We can also analyze the profitability of politicians’ trades themselves:

# Filter purchases

df_buys = df[df[‘Transaction’]==’Purchase’]

# Calculate return between purchase and today’s price 

df_buys[‘Return’] = (get_current_price(df_buys[‘Ticker’]) – df_buys[‘Price’]) / df_buys[‘Price’]

# Aggregate statistics

mean_return = df_buys[‘Return’].mean()

pct_profitable = (df_buys[‘Return’] > 0).mean() 

print(f”Average Return: {mean_return:.2%}”)

print(f”Percentage Profitable: {pct_profitable:.2%}”)}

(embed code)

This calculates the return earned on politicians’ purchases and summarizes the percentage that was profitable.

FAQs

Is it legal to trade on Congressional stock trading data?

Yes, the trades themselves are legal and publicly disclosed. However, utilizing non-public Congressional knowledge to trade would constitute illegal insider trading.

How quickly are politicians’ trades disclosed?

Under the Stock Act, trades must be disclosed within 45 days. However, many file earlier than the deadline.

Where can I find free Congressional trading data?

Quiver Quant and Unusual Whales offer free APIs to access Congressional trading data. The House Stock Watcher and Senate Stock Watcher also provide disclosures.

What analysis can I perform on the trading data?

You can backtest trading strategies based on politicians’ filings, predict future trading activity with machine learning, or simply analyze the performance statistics of the trades themselves.

Which politicians are the best stock pickers?

Academic studies have found mixed performance for Congressional trades. However, traders often track those by Nancy Pelosi, Mitch McConnell, and other prominent representatives and senators.

To Recap

Analyzing and trading based on politicians’ stock moves presents an interesting investment strategy given the data’s transparency. However, further analysis of legal and ethical considerations is warranted.

I hope this overview gives you a starting point for utilizing the publicly available Congressional trading databases that exist today. Please reach out with any questions!

In another related article, StocksToTrade University Review: Key Features, Pricing and More

TAGGED:Finance Tips
Share This Article
Facebook Email Copy Link Print
Leave a Comment Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

Insurance Icon

Get Cheaper Car Insurance in 2025!

Save up to 40% without cutting coverage

Compare Quotes Now
Fast. Free. No obligation.

Popular Articles

Insurance

General Liability Insurance

April 4, 2025
Tax Free Municipal Bonds

Tax-Exempt Municipal Bond

April 4, 2025
Rent vs Buy: Real Estate

Rent vs Buy: Real Estate

April 4, 2025
Growth Stock

Growth Stock

April 4, 2025

Follow US: 

Quick Access

  • About Us
  • Contact
  • Disclaimer
  • Editorial Policy
  • Privacy Policy
  • Terms and Conditions

Cookies Notice

We use our own and third-party cookies to improve our services, personalise your advertising and remember your preferences.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?