Introduction
![How to Track and Analyze Politicians Stock Trades](https://www.financedevil.com/wp-content/uploads/2024/01/Politicians-Stock-Trades-1024x614.jpg)
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.
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