How To Trade Distressed Stocks Using Free APIs

Harry Sauers
Dec 19, 2019 · 5 min read

The Current Ratio

The Current Ratio is a vital metric for understanding a company’s liquidity position as well as its ability to pay its obligations on time. It is defined simply as the company’s total current assets divided by its current liabilities. Current assets are defined as assets that are cash or expected to become cash within one year, and current liabilities are liabilities that will be due in a year or less, such as lines of credit, accounts payable, and sometimes, longer-term debt that is due.

This tutorial will demonstrate how to use’s free API to screen for companies that may have a hard time meeting their obligations (therefore, possibly raising capital on unfavorable terms in the near future) and/or companies that run the risk of defaulting on their obligations. Also provided is an example of a market-neutral strategy for using quant-oriented broker, Alpaca. You’ll be able to learn how to short components of the Nasdaq-100 with low current ratios and go long on the QQQ ETF in equal proportions, which has some anecdotal evidence of generating alpha. For example, a modified version of this theory has been tested in paper trading over the past quarter, and generated returns above the index by 2.8% while remaining market neutral. However, it’s important to note that past performance is not indicative of future results.

Full Code

Getting Set Up

First, get a list of current Nasdaq-100 components. You’re welcome to use this example list from CNBC, or feel free to use any universe of stocks you wish. If you have a text file containing these tickers called “tickers.txt”, you can simply read them into a List with the following code:

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

Great! Now, head over to and sign up for an API key. Set up your API credentials in the program like below:

tenquant_key = 'FAKE_KEY'
tenquant_base_url = ''

Install the Alpaca Python API:

pip3 install alpaca_trade_api

And set up your credentials:

import alpaca_trade_api as tradeapi
key = 'FAKE_KEY'
secret = 'FAKE_SECRET'
base_url = ''
api = tradeapi.REST(key, secret, base_url, api_version='v2')
account = api.get_account()

Finally, to import a couple more libraries use:

import requests
import json

Now, time to get to analyzing individual stocks from your list.

Analyzing Stocks

Recall that the current ratio of a stock is the company’s current assets divided by its current liabilities. Cycle through the list of tickers and identify the current ratio for each one.

First, create a dictionary to hold your data:

all_stocks_data = {}

Then, cycle through all of your tickers:

for stock in tickers:

First, generate the API request to fetch data on that particular stock:

    request_url = (tenquant_base_url + '/data?ticker={TICKER}&key={KEY}').replace('{TICKER}', stock).replace('{KEY}', tenquant_key)

Next, fetch the fundamental data on the stock from the TenQuant API:

    stock_json = requests.get(request_url).content

Make sure that everything works and the data gets stored in a Python dictionary:

stock_data = dict(json.loads(stock_json))
if 'error' in stock_data.keys():
continue # skip this ticker if there is an error

Fetch current assets and current liabilities from the stock’s fundamental data:

    current_assets = stock_data['currentassets']    current_liabilities = stock_data['currentliabilities']

Compute the stock’s current ratio:

    current_ratio = current_assets / current_liabilities

Add the current ratio to your dictionary so you can work with it later:

    all_stocks_data[stock] = current_ratio

Great! Now you have the data you need to perform analysis. All you need to do now is pick out your shorts based on the information you just gathered (and calculated).

Picking Out Stocks

Based on the idea for this algorithm, you’ll want to pick out stocks with the lowest current ratio(s) and short them. Start by sorting your dictionary:

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

Pick out the bottom 20% (or whatever percent you choose) to go short:

shorts = all_stocks_data[:int(len(all_stocks_data)/5) + 1]
print('Shorts: ')

Placing Orders

Here comes the fun part: paper trading. In this part of the tutorial, use the Alpaca API to place orders to short the stocks you selected with low current ratios and go long the QQQ ETF in equal parts.

Calculate the number of shares for each:

weightings = {}
portfolio_value = float(account.portfolio_value)
for stock, current_ratio in shorts:
price = api.get_barset(stock, "minute", 1)[stock][0].c
weightings[stock] = -((portfolio_value/2) / len(shorts)) / price
qqq_price = api.get_barset('QQQ', "minute", 1)['QQQ'][0].c
weightings['QQQ'] = (portfolio_value/2) / qqq_price

Finally, place your order(s) in your Alpaca paper trading account!

for short_stock in weightings.keys():
qty = int(weightings[short_stock])
if qty < 1:
side = 'sell'
side = 'buy'
qty = abs(qty)
# place orders
api.submit_order(short_stock, qty, side, "market", "day")
print("Market order of | " + str(qty) + " " + short_stock + " " + side + " | completed.")
print("Order of | " + str(qty) + " " + short_stock + " " + side + " | did not go through.")

Make it Your Own

There are several ways to improve upon this algorithm for real-money (aka, live) trading, such as factoring in interest expense, the debt to equity ratio, and/or integrating technical analysis into your algorithm. For example, one way to “adjust” the current ratio is by adding the past year (or 4x the last quarter) of operating earnings to current assets. This “adjustment” penalizes cash-burning firms and rewards cash-generating ones.

Happy trading!

Technology and services are offered by AlpacaDB, Inc. Brokerage services are provided by Alpaca Securities LLC (, member FINRA/SIPC. Alpaca Securities LLC is a wholly-owned subsidiary of AlpacaDB, Inc.

You can find us @AlpacaHQ, if you use twitter.

Follow Automation Generation, a Medium’s publication created for developers/makers in trading and fintech.

Automation Generation

News and thought leadership on the changing landscape of automated investing. Changing the market one algorithm at a time.

Harry Sauers

Written by

Writing about software, cybersecurity, and finance.

Automation Generation

News and thought leadership on the changing landscape of automated investing. Changing the market one algorithm at a time.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade