Trading on the Edge: How This Free API Helps Me Find Undervalued Stocks (2024)

Trading on the Edge: How This Free API Helps Me Find Undervalued Stocks (3)

When companies report their quarterly earnings, they are required to include “unusual” items that do not normally occur in the normal operations of the business in their income statements. These charges, often including merger and acquisition charges, or one-time write-downs of an asset, are deducted from net income.

These adjustments can cause investors to overreact to bad news — something that efficient markets purists don’t believe is possible. However, In “Core Earnings: New Data and Evidence”, Ethan Rouen and Charles Wang of Harvard Business School and Eric So of MIT demonstrated that these short-term adjustments really do skew prices.

It is possible to leverage this research with the free TenQuant.io fundamentals API and Alpaca’s commission-free trading platform to then trade using an algorithm based off of this theory. In fact, this is a tutorial to do exactly that.

Full Code:

Setup

Install the Alpaca Trading API:

pip3 install alpaca_trade_api

Before doing much real coding, make sure to have all the dependencies. Import them at the top of the Python program:

import requestsimport jsonimport alpaca_trade_api as tradeapi

Set up an Alpaca account and get API keys. Using a paper trading account before live trading (trading with real money) is suggested.

API Integration

Enter the following keys into your Python program (this is not secure — use command-line arguments or system variables for a production program):

key = 'FAKE_KEY'secret = 'FAKE_SECRET'

Set up the connection to Alpaca’s brokerage and make sure it works:

base_url = 'https://paper-api.alpaca.markets'api = tradeapi.REST(key, secret, base_url, api_version='v2')account = api.get_account()print(account.status)

Run the program! It should print out “ACTIVE” to indicate that the account is live.

Next, search through a list of stocks to find those with the most over- and under-stated earnings. Get a free API key from TenQuant.io in order to access this fundamental data. Use the /earningsreport API endpoint to fetch the latest available financial data.

Set up the TenQuant API connection:

tenquant_key = 'FAKE_KEY'
tenquant_base_url = 'https://api.tenquant.io'

Fetch Stock Data

Add in a list of tickers to search, or pull in from a file:

tickers_list = []
with open('tickers.txt', 'r+') as tickers_file:
tickers_list = tickers_file.read().splitlines()

Add a dictionary to hold the earnings data —index it by ticker:

stocks_data = {}

Finally, get some key data on each stock:

for ticker in tickers_list: # build url request_url = (tenquant_base_url + '/data?ticker={TICKER}&key={KEY}').replace('{TICKER}', ticker).replace('{KEY}', tenquant_key)
# get json response ticker_json = requests.get(request_url).content # make sure everything works and make a Pytohn dict from the json try: ticker_data = dict(json.loads(ticker_json)) except: continue if 'error' in ticker_data.keys(): continue # extract key data points net_income = ticker_data['netincomeloss'] operating_income = ticker_data['operatingincomeloss']

Save the Data

Now for some math to figure out the percentage effect of non-operating earnings on the latest income statement:

 non_operating_income = float(net_income) - float(operating_income)
non_operating_income_percent = non_operating_income / abs(float(net_income))

Add this to the dictionary, using the stock ticker as a key:

stocks_data[ticker] = non_operating_income_percent

This will allow for easier data sorting later.

Analyze Data

Now, outside of the original loop, the data needs to be broken up into two lists of stocks: the ones with the most negative impact of non-operating earnings, and the ones with the most positive impact of non-operating earnings.

sorted_stocks_data = sorted(stocks_data.items(), key=lambda x: x[1])

Now, to find the most understated 10% of company earnings:

understated_ten_percent = sorted_stocks_data[:int(len(sorted_stocks_data)/10) + 1]

And the most overstated 10%:

overstated_ten_percent = sorted_stocks_data[-int(len(sorted_stocks_data)/10) - 1:]

Print to make sure the program works:

print('Understated 10%: ')
print(understated_ten_percent)
print('Overstated 10%: ')
print(overstated_ten_percent)

Time to Buy!

Finally, go ahead and go long on the stocks with understated earnings and short the stocks with overstated earnings:

for long_stock, difference in understated_ten_percent: qty = 1 side = 'buy' try: api.submit_order(stock, qty, side, "market", "day") print("Market order of | " + str(qty) + " " + stock + " " + side + " | completed.") except: print("Order of | " + str(qty) + " " + stock + " " + side + " | did not go through.")
for short_stock, difference in overstated_ten_percent: qty = 1 side = 'sell' try: api.submit_order(short_stock, qty, side, "market", "day") print("Market order of | " + str(qty) + " " + short_stock + " " + side + " | completed.") except:print("Order of | " + str(qty) + " " + short_stock + " " + side + " | did not go through.")

Check the Alpaca dashboard to make sure everything is being executed properly.

Good luck and happy trading!

Find the complete code on GitHub here: https://github.com/hsauers5/AlpacaDemo/blob/master/alpaca.py

If you want to continue to improve on this strategy:

Try the following!

  • Add in technical indicators
  • Use other endpoints from TenQuant.io to get a more detailed picture of the fundamentals.
  • Change portfolio weightings to be equal-weight, rather than one share each.
  • Schedule a function to run this program quarterly/weekly/etc.

*You should know that the use or granting of any third party access to your account information or place transactions in your account at your direction is solely at your risk. Alpaca does not warrant against loss of use or any direct, indirect or consequential damages or losses to you caused by your assent, expressed or implied, to a third party accessing your account or information, including access provided through any other third party apps, systems, or sites.

**Please note that technology and services are offered by AlpacaDB, Inc. and brokerage services are provided by Alpaca Securities LLC, member FINRA/SIPC. Alpaca Securities LLC is a wholly-owned subsidiary of AlpacaDB, Inc.

***Commission-free trading means that there are no commission charges for Alpaca self-directed individual cash brokerage accounts that trade U.S. listed securities through an API. Relevant SEC and FINRA fees may apply.

***This is not an offer, solicitation of an offer, or advice to buy or sell securities, or open a brokerage account in any jurisdiction where Alpaca is not registered (Alpaca is registered only in the United States).

Trading on the Edge: How This Free API Helps Me Find Undervalued Stocks (2024)
Top Articles
Latest Posts
Article information

Author: Kerri Lueilwitz

Last Updated:

Views: 5800

Rating: 4.7 / 5 (67 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Kerri Lueilwitz

Birthday: 1992-10-31

Address: Suite 878 3699 Chantelle Roads, Colebury, NC 68599

Phone: +6111989609516

Job: Chief Farming Manager

Hobby: Mycology, Stone skipping, Dowsing, Whittling, Taxidermy, Sand art, Roller skating

Introduction: My name is Kerri Lueilwitz, I am a courageous, gentle, quaint, thankful, outstanding, brave, vast person who loves writing and wants to share my knowledge and understanding with you.