Trade alongside the insiders with the API

blog photo
Joanne SnelFebruary 4, 2022

‘Insider trading’ has a pretty bad connotation. And for good reason, if insiders are using non-public information to inform their trading habits, that would pose as an unfair advantage on the stock market (also, this is very illegal). For companies publicly listed in the United States, certain employees are required to report any holdings, sales and purchases of their company’s securities to the Securities and Exchange Commission (SEC) in the effort to mitigate the information asymmetry that may arise otherwise. In other words, if reported according to the rules set forth by the SEC, insider trading is completely legal. Luckily, this information is publicly available. We can leverage this data to inform our trades under the expectation that insider trades are informative. We might assume that if insiders are buying their company’s stock, they might expect the stock price to increase in the future (which means we should also place a buy order). 

In this article, we’re going to explore the implications behind following insider trades and write an automated trading strategy that uses this information to place trades using the trading API. Find the full code in this GitHub repository.

Title Card for "Trade alongside the insiders with the API"

Why listen to the insiders? 👂

Academic literature remains divided on the information gain from following insider trades. Several papers suggest that insider trades can predict stock returns, some suggest that not all insider trades are informative and others show that following insider trades in the long term can lead to negative returns. Therefore, it’s important to do your own research and supplement the information obtained from insider trades with additional research.

In the United States, officers, directors and shareholders holding more than 10% of a company’s outstanding stock must file an SEC Form 4 whenever they trade their company’s securities. Following each buy/sell order or option exercise, these so-called ‘insiders’ must report to the SEC within two working days. The information on this form becomes public record — for example, see the following Form 4 filed by the CPO of Coinbase Global, Inc. on 6 January 2022. 

Filing Sheet

If you want to take a closer look, this filing can be found here

You’ll notice that Chatterjee reported the security he traded, the type of trade, the amount and at what price. There are a number of reasons why he might place such a trade. For example, he might have insights into the company’s projected performance (note that insider trading is only illegal when it is not publicly reported). Or, he might simply be selling for liquidity or diversification purposes. It’s difficult to discern for what reason an insider is trading purely by looking at this data, but it might be indicative of future stock returns. 

Automating insider knowledge 🤖 

In order to automate trades based on insider trades, we need to:

  • obtain insider trades, 
  • determine whether that company is tradable on the exchange you’re using,
  • set up certain trade rules,
  • place your trades with and 
  • schedule your code to run at regular intervals. 

If you’re interested in the steps, keep reading. Otherwise, you can find the GitHub repository, here

Obtaining insider trades 🔍 

Form 4 information is publicly listed on the SEC website, but there are third-party providers that report this information in an easily legible format. This means that everything you need is in one place, removing the need to parse through all submitted SEC forms. For this tutorial, we decided to go with FinViz, but OpenInsider is another good option.

A screenshot of the FinViz page, taken on 30 January 2022. 

A screenshot of the FinViz page, taken on 30 January 2022. 

We scraped the information using the requests library and BeautifulSoup. If you’d like to see a more in-depth explanation of this scraping process, you can follow the steps outlined in this article

Is it tradable? ✅

Before we can set up our trade rules, we need to do some general housekeeping on the data. For example, because SEC filings concern companies publicly listed in the US, tickers listed on FinViz are those corresponding to American exchanges. Therefore, in order to trade on, we need to obtain the corresponding German ticker. This can be done by using the OpenFIGI API, as shown in this article. If the German ticker cannot be found, we drop the instrument from the dataset. 

Setting up the trade rules 🤔 

After your dataset is usable, all that’s left is setting up the trading logic and order execution. Which decision rules you settle on is entirely up to you, but we’re using some of the general guidelines listed in this Investopedia article. For our example project we only consider buy or sell orders placed by company executives because those at the head of the company probably know more about the company’s future compared to directors. In addition, we also only consider trades when they constitute more than 1% of that individual’s total holdings. In our project, this is translated to code as follows:

1def get_trade_decisions(self):
2    buy = set()
3    sell = set()
4    # directors know less about a company's outlook than executives
5    trusted_relationships = ["CEO", "CFO", "COO", "CTO"]
6    for index, row in self._df.iterrows():
7        transaction_type = row["Transaction"]
8        relationship = row["Relationship"]
9    # if insider buys large amount, we also want to buy
10    if transaction_type == "Buy" and (relationship in trusted_relationships or "Officer" in relationship):
11        if row["Number of Shares"] / row["Total Shares"] > 0.01:  # trade >1% of total shares
12            buy.add(row["isin"])
13            print(f'Buy {row["gm_ticker"]}.')
14        # if insider sells large amount, we also want to sell
15    elif transaction_type == "Sale" and (relationship in trusted_relationships or "Officer" in relationship):
16        if row["Number of Shares"] / row["Total Shares"] > 0.01:  # trade >1% of total shares
17            sell.add(row["isin"])
18            print(f'Sell {row["gm_ticker"]}.')
19    return buy, sell

This method returns two sets: a selection of instruments to buy and a selection of instruments to sell.

Placing trades with 🍋 

The trading API makes it easy to execute orders once you’ve decided which instruments to trade. With two POST requests, you can place and activate your orders: 

1def post_data(self, endpoint: str, data):
2    response =
3      self.url_trading + endpoint, json.dumps(data), headers=self.headers)
4    return response.json()
6def place_order(self, isin: str, expires_at: str, quantity: int, side: str):
7    venue = os.environ.get("MIC")
8    order_details = {
9      "isin": isin,
10      "expires_at": expires_at,
11      "side": side,
12      "quantity": quantity,
13      "venue": venue
14    }
15    return self.post_data(f"orders/", order_details)
16def activate_order(self, order_id: str):
17    return self.post_data(f"orders/{order_id}/activate/", {})

This code snippet is incomplete and for illustrative purposes only, see the full GitHub repository for a complete overview. 

Scheduling your code ⏰

In order to ensure that the code executes autonomously, we’ve used the Advanced Python Scheduler library to scrape the website once every weekday and place trades if the inside trades adhere to the decision rules we defined above. 

Further improvements 🛠

This project provides a solid starting point, but can be extended to reflect your customised priorities. As follows, a few suggestions:

  • only consider cluster buying, i.e. 3+ executives trading within a short amount of time,
  • only consider small- to mid-size companies because executives probably have a more holistic view of business operations (compared to those at the head of large companies), 
  • only trade based on recent information, i.e. drop datapoints more than 3 days old, 
  • ensure that you’re not using the same information twice, i.e. store past trades. 

Besides these improvements, perhaps you also want to host your strategy in the cloud such that it is always running. 

In broad lines, that’s about all you need to know to start setting up your insider trades following strategy. Clone the repository and get started adding your own adjustments! If you’re not yet a part of, you can sign-up here

If you have any questions, feel free to reach out to us at or join our vibrant Slack community. Thanks for reading and happy trading!

Joanne from 🍋.markets

The content of this article is not investment advice. It is for general, educational purposes only and does not take into account your individual needs.

You might also be interested in

blog photo

Blog 38 - The market maker explained

Market Makers are crucial to provide liquidity to stock exchanges. In this blog post, we talk about what Market Makers do and why they are useful.

blog photo

5 (+1) YouTube channels for FinTech enthusiasts 

YouTube is a great way to learn about new things, including financial education or coding. Therefore, in this article we’d like to introduce you to 5 YouTube channels to level up your trading literacy.

blog photo

A short introduction to derivatives

In this article, we'd like to introduce you derivatives - they come up in finance and leave a lot of people scratching their heads, though it's totally worth it! Curious about hearing what's the difference between investing and trading, the coherence between finance and weather & why the Greeks even appear here? We'll discuss who’s using them, what they are and how they can be valued in the following.

Dive Deeper

Find more resources to get started easily

Check out our documentation to find out more about our API structure, different endpoints and specific use cases.


Join community

Join our Slack channel to actively participate in our community, ask questions to other users and stay up to date at all times.


Interested in building with us?

We are always looking for great additions to our team that help us build a brokerage infrastructure for the 21st century.

Need any help?
Ask a question in our CommunityAsk a question in our CommunityGet started with our DocumentationGet started with our DocumentationGet inspired on our BlogGet inspired on our Blog
© 2021Privacy PolicyImprint
All systems normal

As a tied agent under § 3 Sec. 2 WplG on the account and under the liability of DonauCapital Wertpapier GmbH, Passauer Str. 5, 94161 Ruderting (short: DonauCapital), GmbH offers you the receipt and transmission of orders for clients (§ 2 Sec. 2 Nr. 3 WpIG) of financial instruments according to § 3 Sec. 5 WpIG as well as brokerage of accounts.