Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Algorithmic Short Selling with Python
  • Table Of Contents Toc
Algorithmic Short Selling with Python

Algorithmic Short Selling with Python - Second Edition

By : Laurent Bernut
close
close
Algorithmic Short Selling with Python

Algorithmic Short Selling with Python

By: Laurent Bernut

Overview of this book

Algorithmic Short Selling with Python, Second Edition is a practical guide to building, testing, and managing systematic short-selling strategies in today's markets. Structured around the core challenges every short seller faces, the book provides a framework for continuously generating long/short ideas, identifying bullish/bearish market regimes, detecting sector rotation ahead of consensus, constructing robust long/short portfolios, and managing the unique risks of the short side. Through real-world examples and working Python code based on S&P 500 data, readers learn how to develop quantitative strategies that address position sizing, crowded trades, portfolio exposures, and capital allocation across changing market conditions. The book also explores advanced topics such as relative strength analysis, fractals, convexity, long/short portfolio management, asset allocation, and the use of AI-powered trading journals to uncover the behavioral patterns that influence trading decisions. Every concept is supported by implementation, bridging the gap between theory and execution. Expanding on the first edition, this updated version transforms ideas into fully coded solutions, providing readers with the tools to design, evaluate, and deploy systematic short-selling strategies with confidence, discipline, and consistency.
Table of Contents (16 chapters)
close
close
Lock Free Chapter
1
Part 1: The Short Selling Game
5
Part 2: The Outer Game: The Trading Edge
10
Part 3: The Long/Short Game: Portfolio Construction
15
Index

Preface

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:

  • Abundance of ideas: by Chapter 4, you will consistently generate more ideas than you have capital to deploy.
  • Calibrated risk management: short selling is not a stock-picking contest; it is a position sizing and risk management exercise.
  • You will learn portfolio management and asset allocation techniques that can produce a smooth equity curve across market conditions.

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 47) 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.

Who this book is for

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.

What this book covers

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.

To get the most out of this book

  • A good knowledge of financial markets is assumed. The material has resonated more deeply with market participants who have experienced a drawdown. They tend to be more open to exploring new approaches.
  • An intermediate level of Python is assumed. Experienced programmers will likely refactor the code to their own standards, and that is actively encouraged. All packages and libraries used in this book are free and open-source. For any library not already installed on your system, the standard approach is: pip install ––upgrade library_name.

Download the example code files

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:

  1. Go to packtpub.com
  2. Click your profile picture and select Your Orders
  3. Find this book and click Download Code

If you bought this book from Amazon or any other channel partner:

  1. Go to https://packtpub.com/unlock or scan the following QR code:

    Image

  2. Search for this book
  3. Sign up or log in to your free Packt account
  4. Upload your proof of purchase and download the code bundle locally

Usage note: You're free to use and modify this code for personal learning and non-commercial projects.

Download the color images

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.

Conventions used

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.

Get in touch

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 .

Share your thoughts

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.

CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Algorithmic Short Selling with Python
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon