-
Book Overview & Buying
-
Table Of Contents
Algorithmic Short Selling with Python - Second Edition
By :
Every market participant wants the same thing: the quiet confidence to make money even in terrible markets. A robust way to achieve that peace of mind is to learn to sell short. Short selling is one of the least understood and most reviled disciplines in modern finance. Yet, there is money to be made. Of the original S&P 500 constituents, only 10% remain in the index today. The rest have been merged, replaced, and churned. Every deletion was a short seller's opportunity.
Short selling is not an art. It is discipline. This skill is uniquely demanding in ways the long side is not. Successful short positions contract, while unprofitable ones expand, continuously dislocating exposures in the wrong direction. This mechanical asymmetry demands a systematic response. Algorithmic trading lends itself naturally to short selling. It can process vast quantities of data, screen entire markets consistently, and remove the emotional friction that derails human judgment at precisely the wrong moment.
Even if you choose never to sell short, the concepts and techniques in this book will sharpen your analytical repertoire. Risk management, regime detection, position sizing, portfolio management, and asset allocation are universal disciplines.
This book makes three promises:
The book is organized into three parts. Part 1 (Chapters 1–3) lays out the philosophical and mathematical foundations and dispels the most pervasive myths surrounding short selling. Part 2 (Chapters 4–7) dives into practical implementation using Python, pandas, numpy, yfinance, ArcticDB, and mplfinance, from downloading S&P 500 price data to constructing relative weakness metrics, defining market regimes, sizing positions, and building a complete long/short portfolio engine. Part 3 (Chapters 8–10) covers portfolio construction, risk management, asset allocation, and the trading journal: how to manage exposures, allocate capital across strategies with Dynamic Exposure Allocation, and close the loop with a complete Airtable-based trading journal, powered by AI, that tracks both trade analytics and the subconscious mental patterns that silently determine long-term performance.
This book will guide you through a complete, end-to-end framework for algorithmic short selling: from the first line of code to the final journal entry, from individual stock selection to portfolio-level asset allocation. Theory is always paired with implementation, and every concept is grounded in real market data. Most of the examples use S&P 500 constituents as the investment universe, but the methodology applies equally to any liquid equity market globally. The author has been active for over two decades in Japan equity long/short.
This second edition is radically different from the first. The code in the first edition got the job done, but nobody would accuse it of being beautiful. The code has been completely refactored: concepts that could only be described in theory are now fully implemented. Powerful new ideas have been introduced: regime definition using Mandelbrot's fractals, dynamic portfolio management, Dynamic Exposure Allocation, and an AI-powered trading journal. The architecture has been rebuilt from the ground up.
Making money on the markets is hard. Making money selling short is even harder. The purpose of this book is to demystify short selling and make it accessible to more market participants. This is the book I wish I had had two years into my career as an investment professional, combining theory with practical code and decades of experience.
This book is for quantitative traders, portfolio managers, algorithmic trading developers, and advanced retail traders who want to master the short side using Python. A working knowledge of Python and basic trading concepts is assumed. Readers will gain not just coding skills, but also the strategic and risk management frameworks needed to build profitable short strategies.
Chapter 1, The Stock Market Game, sets the stage for the entire book. It frames the stock market as a complex, infinite, and random game, introduces the mindset required to stay in it, and makes the case for short selling as an indispensable algorithmic discipline.
Chapter 2, 10 Classic Myths About Short Selling, dispels the ten most pervasive myths surrounding short selling, from the claim that short sellers destroy pensions to the fiction of unlimited loss potential, and replaces them with data, logic, first-hand experience, and market history.
Chapter 3, Long/Short Methodologies: Absolute and Relative, demonstrates how to generate an abundance of short ideas using both absolute and relative series. It shows why the relative weakness method dramatically outperforms the absolute approach and how sector rotation analysis lets the market do the heavy lifting.
Chapter 4, Regime Definition, covers a full range of regime definition methodologies: breakout, turtle trader logic, moving average crossovers, fractals, higher highs and lows, floor and ceiling, and a composite scoring system. It highlights fractals as a powerful indicator that folds naturally across timeframes.
Chapter 5, The Trading Edge Is a Number, and Here Is the Formula, reveals the trading edge formula and gain expectancy. It explores the two strategy archetypes: trend following (right skew) or mean reversion (left skew), and implements a pairs trading strategy across S&P 500 sectors.
Chapter 6, Position Sizing: Money Is Made in the Money Management Module, demonstrates that money is made in the money management module. It compares fixed percentage, fixed risk, volatility-adjusted, and Kelly-based position sizing algorithms and measures their distinct impact on the equity curve.
Chapter 7, Refining the Investment Universe, narrows the investment universe to tradable short ideas. It applies liquidity screens and crowded-short filters, shows how to short high-dividend value traps, identifies the precise moment when fundamental analysis adds value, and calculates rolling beta across the S&P 500.
Chapter 8, The Long/Short Toolbox, assembles the complete long/short toolbox. It brings regime signals, position sizing, and universe filters into an integrated portfolio engine, and covers the four key exposures: gross, net, net beta, and concentration. It then introduces the convex oscillator as a powerful tool to collapse risk.
Chapter 9, Asset Allocation, models strategy returns rather than asset prices, distinguishing left-skewed from right-skewed payoff profiles. It runs classic asset allocation algorithms and introduces Dynamic Exposure Allocation, a system-failure-based framework for deploying capital across strategies.
Chapter 10, The Trading Journal, focuses on debugging the programmer, not just the code. It builds a complete trading journal on Airtable: Part A automates trade reconciliation and audit trails; Part B automates the psychology journal with gamification, and an AI layer analyzes both as a trading psychologist would.
library_name.This book includes a complete downloadable code bundle containing all the example projects and files used throughout the chapters. We recommend downloading the bundle so you can follow along smoothly and experiment with the examples.
Use the bundle as a practical starting point. Modify it, extend it, and apply what you learn by creating your own variations as you progress through the chapters.
Get the code bundle
If you bought the book directly from Packt:
If you bought this book from Amazon or any other channel partner:

Usage note: You're free to use and modify this code for personal learning and non-commercial projects.
Your purchase includes a color, DRM-free PDF copy of this book, ideal for viewing color images, screenshots, and diagrams. Refer to Free benefits with your book section at the end of the Preface to unlock your PDF copy.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example: "We slice results_df (already sorted by Sharpe descending) into top_n (best 10) and bottom_n (worst 10)."
A block of code is set as follows:
short_float = sp500_info_df['shortPercentOfFloat'].rank(pct=True).sort_values(ascending=False).index[:10].tolist()
sp500_info_df.loc[high_short_float, ['shortName','sector','shortPercentOfFloat', 'shortRatio']].round(3).head(10)
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
import pandas as pdimport numpy as npimport requestsfrom io import StringIOimport arcticdb as adbfrom arcticdb import LibraryOptionsimport yfinance as yf%matplotlib inlineimport matplotlib.pyplot as plt
Any command-line input or output is written as follows:
pip install –upgrade library_name
Bold: Indicates a new term, an important word, or words that you see on the screen. For instance, words in menus or dialog boxes appear in the text like this. For example: "A side effect and classic pitfall for intermediate short sellers of over-filtering are false negatives."
Warnings or important notes appear like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book or have any general feedback, please email us at [email protected] and mention the book's title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you reported this to us. Please visit http://www.packt.com/submit-errata, click Submit Errata, and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit .
Once you've read Algorithmic Short Selling with Python, Second Edition, we'd love to hear your thoughts! Please for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we're delivering excellent quality content.
Change the font size
Change margin width
Change background colour