FAQ · Getting systematic research right

How do I include short-selling borrow costs in a backtest?

Charge each short trade its borrow fee, the annual rate times the value borrowed times the days held over 360, and check that the stock could be borrowed at all. Easy-to-borrow large caps cost well under 1% a year; hard-to-borrow names can cost many times that, and those are often the stocks a short-selling rule picks.

Charge each short trade its borrow fee, the annual rate times the value borrowed times the days held over 360, and check that the stock could be borrowed at all. Easy-to-borrow large caps cost well under 1% a year; hard-to-borrow names can cost many times that, and those are often the stocks a short-selling rule picks.

What a short actually costs

  • Borrow fee. To sell a stock you do not own, your broker borrows it and charges a fee on its value for every day the short is open. US brokers usually accrue it daily on a 360-day year.
  • Dividends. A short pays any dividend that goes ex while it is open. On adjusted prices this is already in the returns; on raw prices, charge it.
  • Availability. A stock with no shares to lend cannot be shorted, and a lender can recall shares, forcing you to buy back.
  • Spread, slippage and commission, as on any trade.

Why borrow cost matters more than it looks

The rate varies by stock and by day. Shorts of small, crowded or heavily shorted stocks, which many short rules select, can carry rates of tens of percent a year. A short rule that earns 15% a year on paper may earn nothing after borrowing hard-to-borrow names. Your broker publishes current rates; historical rates come from securities-lending data vendors.

How to charge it

For each closed short trade:

borrow = qty × entry price × annual rate × days held / 360

This uses the entry value. The fee actually accrues on each day's market value, but entry value is close enough for most holding periods.

How Reamer Research handles it

Reamer Research reports every closed trade with its side, entry price, quantity and timestamps, so borrow is charged after the run, per trade, at any rate you have. This class trades both sides; the code after it charges a flat rate per ticker to the shorts:

from datetime import datetime
import reamer_research as rr

class Reversal:
    lookback = 25
    def on_bar(self, d):
        if d.close[0] == 0 or d.position() != 0:
            return None
        mean, sd = d.close.mean(), d.close.std()
        if d.close[-1] > mean + 2 * sd:
            return rr.sell_market(10, take_profit=mean, stop_loss=d.close[-1] + 2 * sd)
        if d.close[-1] < mean - 2 * sd:
            return rr.buy_market(10, take_profit=mean, stop_loss=d.close[-1] - 2 * sd)

BORROW = {'SPY': 0.0025}                                  # 0.25% a year
result = rr.backtest(Reversal, {'SPY': 'data/SPY_5min.bin'}, spread=0.01)
def days_held(t):
    held = datetime.fromisoformat(t['close_timestamp']) - datetime.fromisoformat(t['open_timestamp'])
    return held.total_seconds() / 86400

borrow = sum(t['qty'] * t['entry_price'] * BORROW[t['ticker']] * days_held(t) / 360
             for t in result.closed_trades if t['side'] == 'sell')
print(f'net {result.net_pnl:.2f}, borrow {borrow:.2f}, after borrow {result.net_pnl - borrow:.2f}')

A short trade has side 'sell'. A dict of rates per ticker, or a table of rates per day loaded with pandas, plugs into the same sum. The class could equally be an on_bar(data) function, or an object configured with its band width.

Limits to know

  • The engine's swap_per_unit setting suits FX and CFD financing, where longs pay and shorts receive. For stock borrow, which shorts pay, use the calculation above.
  • Borrow rates and availability are yours to supply. The engine does not hold a stock-loan feed.
  • Evaluation Mode runs 30 days or 50,000 bars of one ticker. Enough to check the calculation on your own shorts; universes need a licence.

A $20 month includes the full kit, so you can charge your own borrow rates to your own short strategy and cancel if it does not fit.

Next questions

How do I model my broker's commissions in a backtest?Copy your broker's actual schedule, per share, per contract or a percentage of value, with its minimum and maximum per order, and charge it on every fill, entries and exits both. For a strategy that trades small orders often, the minimum per order is usually what matters most, and a flat per-share rate without it understates the cost.What is survivorship bias and how do I avoid it?Survivorship bias is testing only on assets that still exist today, which leaves out the companies that were delisted, went bankrupt or were acquired. Avoid it by testing on the universe as it was on each date, with delisted names and their final prices included, from a data source that keeps them.How do I backtest a pairs trading strategy with cointegration in Python?Test candidate pairs for cointegration on an in-sample period, estimate the hedge ratio there, then trade the spread out of sample. Go long the spread when its z-score falls below a threshold and short it when it rises above, closing near zero. Estimating the hedge ratio on the whole history is the most common way pairs backtests lie.How realistic do slippage and spread need to be in a backtest?Realistic enough that the result survives them. Set spread, slippage and commission per instrument from what your broker actually charges, let spread and slippage widen when the market moves fast, and then rerun at one and a half and two times those costs. A strategy whose edge disappears under slightly higher costs was never a reliable edge.

Every answer here restates the documents that ship in the kit, which are authoritative. All questions.

Reamer Research

Your first backtest in a minute

Backtesting and live trading in Python and C++. Free to install in Evaluation Mode, with no key or sign-up.

pip install reamer-research

A licence at $20 a month removes every limit. The same code runs unchanged.

Reamer Server

The order-management core for your firm

Your venues, your risk rules on every order, one strategy per CPU core, on your own Linux servers.

$24,000 / year

Or start with a 30-day trial at $2,000.