Analyzing politicians’ stock trading in Python

CHRISTOPHER KARDATZKE
2 min readJan 3, 2021

For the past several months I’ve been scraping data on stock trading by U.S. congressmen and creating visualizations such as the one below showing weekly net stock purchases by senators alongside the market.

As I’ve been sharing these visualizations, I’ve seen a lot of interest in trading off of the data so I wanted to give a tutorial on how to get the data into Python and do some basic analysis of it.

Installing Python

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

Getting the data

You can get data on trading by congressmen using the quiverquant package in Python. In order to install that package, run pip install quiverquant in your terminal.

You’ll need to sign up for Quiver’s API in order to get a token to access the data.

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

In our case, we will fetch recent transactions by Senator David Perdue.

import quiverquant#Replace <TOKEN> with your personal token
quiver = quiverquant.quiver("<TOKEN>")
df = quiver.congress_trading("David Perdue", True)
df.head(10)

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

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()

If there’s sufficient interest I’ll walk through some more complex analysis and backtest some trading strategies using the data in a future blog post, but I wanted to keep the code in this introduction fairly simple.

--

--