liveBook · Manning

Transaction cost

As explained in Investing for Programmers

A transaction fee is a charge incurred when buying or selling a financial asset.

A transaction cost is a charge incurred when buying or selling a financial asset. In algorithmic trading, it converts a paper gain into a more realistic result by reducing returns for each executed transaction. section 11.3.1

The cost matters when comparing a strategy with simply buying and holding an asset. A backtest can subtract a fixed charge, such as $1, for every recorded buy or sell; frequent signals therefore face a larger cost burden. section 11.3.1

Use transaction costs to:

  • Reduce summed trade cash movements by the fee multiplied by the number of transactions. section 11.3.1
  • Set a more demanding benchmark for whether a trading strategy improves on holding shares from the start to the end of a period. section 11.3.1
  • Distinguish ETF expense ratios from the transaction fees avoided by purchasing a diversified fund instead of many underlying stocks separately. section 1.2.3

Applying costs in a backtest

A Python backtest can accept transaction_costs = 1, calculate a strategy’s gain, and then subtract transaction_costs multiplied by the number of recorded cash movements. The resulting gain reflects trading friction rather than an idealized signal-only return. section 11.3.1

Listing 11.2 Executing a single backtest
def run_single_backtest(ticker: str, cash, start_date: str, end_date: str, 
transaction_costs = 1) -> pd.DataFrame:
    df = load_data(ticker, start_date, end_date)
    shares = round(cash / df["Close"][0])
    print(f"Shares: {shares}. start price: {df["Close"][0]}. end price: "
          f"{df["Close"].iloc[-1]}. to beat: {df["Close"].iloc[-1]*shares – 
                                                 df["Close"][0]*shares – 
                                                 transaction_costs}")
    df = add_sma(df, 10, 20)
    res = backtest(df, 10, 20, shares, True)
    gain = res['cash_movement'].sum()
    gain = gain - transaction_costs * len(res['cash_movement'])
    print(f"Gains: {gain})")
    return df
results_nvda
 = run_single_backtest("NVDA", 1000, "2015-01-01", "2025-01-01")

Inspect the single-backtest implementation that loads prices, determines share quantity, records trades, and deducts transaction costs from the reported gain. section 11.3.1

How Investing for Programmers covers it

How deep it goes
Defines the charge and implements fixed per-transaction deductions, without modeling variable fee schedules or market frictions.
Examples
Uses a one-dollar-per-transaction assumption, Python backtests, and ETF-versus-direct-stock-purchase comparisons.
What it assumes
Assumes basic buy-and-sell actions, share quantities, gains, and Python DataFrame workflows.
What you can do after
Apply it via a Python backtest to subtract estimated fees and judge whether strategy gains survive trading costs.
How it connects
Connects transaction costs with backtesting, trading strategies, ETFs, and expense ratios.

Also explained in

Compare how 4 books explain transaction cost →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Investing for Programmers. The section links point to the parts of the book it draws on.