Share E-Book

Algorithmic Short Selling With Python Strategies, signals, and risk management techniques for profitable short trades (Laurent Bernut) (z-library.sk, 1lib.sk, z-lib.sk)

Author

Rating No ratings yet

Log in to rate

Data Structures and Algorithms
Language English

No Description

Format PDF
Size 9.0 MB
6
Views
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
(This page has no text content)
Page 2
Algorithmic Short Selling with Python Second Edition Strategies, signals, and risk management techniques for profitable short trades Laurent Bernut
Page 3
Algorithmic Short Selling with Python Second Edition Copyright © 2026 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. The author acknowledges the use of cutting-edge AI, such as ChatGPT, with the sole aim of enhancing the language and clarity within the book, thereby ensuring a smooth reading experience for readers. It's important to note that the content itself has been crafted by the author and edited by a professional publishing team. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Portfolio Director: Sunith Shetty Relationship Lead: Nilesh Kowadkar Project Manager: Shashank Desai Content Engineer: Nathanya Dias Technical Editor: Aysha Nadeem Indexer: Rekha Nair Production Designer: Salma Patel Growth Lead: Abhishek Kaushik First published: September 2021 Second edition: June 2026 Production reference: 1110626 Published by Packt Publishing Ltd. Grosvenor House 11 St Paul's Square Birmingham B3 1RB, UK. ISBN 978-1-80602-593-0 www.packtpub.com
Page 4
I would like to dedicate this book to Jules and Alizee, who taught me the meaning of unconditional love. When in doubt, remember this: I LOVE YOU. – Laurent Bernut
Page 5
Contributors About the author Laurent Bernut is a hedge fund veteran and short-selling specialist with over 20 years of experience across global financial markets. He has worked for prestigious institutions including Fidelity Japan and two major long/short hedge funds, where he honed his expertise in quantitative trading and portfolio management systems. Laurent has built quantitative trading tools and portfolio management systems used by professionals worldwide. Passionate about education and strategy development, he brings deep insight into market dynamics, risk, and portfolio construction. I would like to extend my sincere gratitude to Nathanya Dias and Shashank Desai for their continuous patient guidance. I would like to thank John Mac Laughlin for being a tough accountability partner. Special thanks to the Aussie wisdom jedis. I would like to thank the ATAA Alan Clement and Jurij Bondaruk. I would like to express my gratitude to Richard Dale at Norgate data for our inspirational conversations. I would also like to thank Nikita Amosov at eodhd. Special thanks to Adrian Stanica and the idea of the journal. Special thanks to Scott Phillips for being a larger than life inspiration. Huge debt of gratitude to June Yon Kim, Basil Dan, and Sakyo Ebihara for keeping me sane. Thank you Frank Fox for being here every time it truly mattered. Heartfelt gratitude to Julius Lilly for his unwavering support. I want to express my gratitude to my children: they have inspired me to create a legacy and taught me the true meaning of unconditional love.
Page 6
About the reviewers David Capablanca is a verified seven-figure short seller with a 90% win ratio who turned $29,000 into seven-figure profits in just four years. After surviving brain tumor surgery while attending UCLA's master's program in architecture, he developed ground-breaking strategies for ethical short selling that have helped thousands of people achieve financial freedom. Through his popular podcast The Friendly Bear, and Friendly Bear University classes and Discord, Capablanca teaches traders to combine technical expertise with mindset mastery. In pursuit of his mission to empower everyday people to take control of their financial futures, he has authored the book Short Selling Master: Proven Strategies from a High-Stakes Day Trader. John Rizcallah, known online as John the Quant, is a mathematician and quant-turned-data- scientist whose work sits at the intersection of causal inference, machine learning, and quantitative finance. He applies mathematical rigor across the full life-cycle of quantitative systems, from strategy research and model development to automated execution and real-world decision-making.
Page 7
(This page has no text content)
Page 8
Table of Contents Preface xvii Free benefits with your book ............................................................................ xxiv Part 1: The Short Selling Game 1 Chapter 1: The Stock Market Game 3 Is the stock market art or science? ......................................................................... 4 How do you win this complex, infinite, random game? .......................................... 5 How do you win an infinite game? ......................................................................... 6 How do you beat complexity? • 7 How do you beat randomness? • 7 Playing the short selling game ............................................................................ 10 Short selling is an algorithmic sport .................................................................... 10 Summary ............................................................................................................ 11 Chapter 2: 10 Classic Myths About Short Selling 13 Myth #1: short sellers destroy pensions ................................................................ 14 Myth #2: short sellers destroy companies ............................................................. 17 Myth #3: short sellers destroy value ..................................................................... 19 Myth #4: short sellers are evil speculators ............................................................ 19 Myth #5: short selling has unlimited loss potential but limited profit potential .... 22 Myth #6: short selling increases risk ................................................................... 24 Myth #7: short selling increases market volatility ................................................ 25 Myth #8: short selling collapses share prices ....................................................... 26 Myth #9: short selling is unnecessary during bull markets ................................... 26 Myth #10: the myth of the "structural shortage" ................................................. 27 Summary ........................................................................................................... 28
Page 9
Chapter 3: Long/Short Methodologies: Absolute and Relative 31 Technical requirements ....................................................................................... 31 Importing libraries ............................................................................................. 32 Long/Short 1.0: the absolute method .................................................................. 32 Ineffective at decreasing correlation with the benchmark • 33 Step 1: building a dataframe of S&P 500 constituents by scraping the internet • 35 Step 2: downloading historical prices using the yfinance library • 36 Step 3: Bullish/Bearish regime for the absolute/relative series • 38 Ineffective at reducing volatility • 39 Little, if any, historical downside protection • 39 Lesser investment vehicles • 39 Laggard indicator • 40 Long/Short 2.0: the relative weakness method .................................................... 40 Consistent supply of fresh ideas on both sides • 48 Focus on sector rotation • 51 Step 1: calculating aggregate average by sector along the horizontal axis • 52 Step 2: plotting sector averages for absolute and relative series • 53 Step 3: cyclicals versus defensives • 54 Step 4: sector averages and rotation • 56 Provides a low-correlation product • 59 Provides a low-volatility product • 59 Reduces the cost of borrow fees • 59 Provides scalability • 60 Nonconfrontational • 60 Currency adjustment becomes an advantage • 60 Step 1: downloading historical prices in local currency • 61 Step 2: converting the prices into USD using the ccy_df • 63 Step 3: calculating cumulative returns in USD • 64 Step 4: building a table of returns • 67 Step 5: building a heatmap function • 67 Other market participants cannot guess your levels • 69 Table of Contents viii
Page 10
Lead the market and look like an investment genius • 69 Summary ........................................................................................................... 72 Part 2: The Outer Game: The Trading Edge 75 Chapter 4: Regime Definition 77 Technical requirements ...................................................................................... 78 Importing libraries ............................................................................................. 78 Utilities functions .............................................................................................. 79 Regime definition: defining methodologies ......................................................... 89 Breakout/breakdown method • 89 Turtle traders • 92 Moving average crossover • 93 Fractals • 94 Higher highs, higher lows • 103 Floor and ceiling • 107 Composite score • 110 ArcticDB set-up ................................................................................................. 114 Defining Arctic database utility functions for data retrieval • 115 Data manipulation across the investment universe ............................................. 116 Data manipulation across the S&P 500 .............................................................. 119 Fractals in production ....................................................................................... 124 Searching for the bar that triggered the bear avalanche ...................................... 127 One-minute data resampling • 128 Summary .......................................................................................................... 135 Chapter 5: The Trading Edge Is a Number, and Here Is the Formula 137 Technical requirements ..................................................................................... 137 Importing libraries ............................................................................................ 138 The trading edge formula .................................................................................. 138 Technological edge • 139 Information edge • 140 ix Table of Contents
Page 11
Statistical edge • 140 A trading edge is not a story .............................................................................. 140 Rudimentary strategy simulation • 143 Signal module: entries and exits • 150 Entries: stock picking is vastly overrated • 151 Exits: the transmutation of paper profits into real money • 152 Regardless of the asset class, there are only two strategies .................................. 153 Trend following • 154 Mean reversion • 158 Pairs trading across sectors of the S&P 500 • 161 Summary .......................................................................................................... 182 Chapter 6: Position Sizing: Money Is Made in the Money Management Module 185 Technical requirements .................................................................................... 186 The four horsemen of apocalyptic position sizing ............................................... 187 Horseman 1: liquidity is the currency of bear markets • 187 Horseman 2: averaging down • 188 Horseman 3: high conviction • 189 Horseman 4: equal weight • 189 Position sizing is the link between emotional and financial capital .................... 190 Importing libraries • 192 Defining arcticdb and utilities functions • 192 Retrieving data from arcticdb and generating dataframes • 194 Converting local currency to USD • 196 Continuous signals and relative series for each stock in the investment universe • 197 Defining position sizing functions • 197 Fixed Dollar/Percentage ................................................................................... 203 Fixed risk position sizing .................................................................................. 208 Volatility ........................................................................................................... 211 Raw volatility • 214 Standard deviation and average true range • 217 Table of Contents x
Page 12
Kelly criterion .................................................................................................. 220 Summary .......................................................................................................... 231 Chapter 7: Refining the Investment Universe 233 Liquidity is the currency of bear markets ........................................................... 233 Importing libraries • 235 Downloading information for all S&P 500 constituents • 235 Extracting useful information for all S&P 500 constituents • 236 Crowded shorts ................................................................................................ 238 The fertile ground of high dividend yields ......................................................... 242 Share buybacks ................................................................................................ 244 Fundamental analysis ....................................................................................... 245 Valuations • 246 Beta ................................................................................................................. 248 Calculating beta from historical prices across the S&P 500 constituents • 248 Calculating average returns by sector • 253 Calculating average returns by sector • 255 Calculating the average returns for the top and bottom 5 betas • 258 Simulating a beta momentum strategy • 260 Summary ......................................................................................................... 262 Part 3: The Long/Short Game: Portfolio Construction 265 Chapter 8: The Long/Short Toolbox 267 The Long/Short toolbox .................................................................................... 268 Technical requirements • 269 Gross exposure ................................................................................................. 269 Dynamic risk appetite management • 273 Net exposure .................................................................................................... 282 Net beta ........................................................................................................... 285 Concentration .................................................................................................. 287 The paradox of low-volatility returns • 288 xi Table of Contents
Page 13
Ratio of big to small bets • 289 Exchange exposure ........................................................................................... 289 Sector exposure ................................................................................................ 290 Design your unique mandate • 291 Summary ......................................................................................................... 292 Chapter 9: Asset Allocation 295 The true meaning of a smooth equity curve ....................................................... 296 The mirage of uncorrelated returns • 296 Why smoothness is difficult to achieve in practice • 297 The two strategy archetypes ............................................................................. 297 Left-skewed strategies • 297 Right skewed strategies • 298 Combined or mixed skew strategies • 299 Model returns instead of asset prices .................................................................. 301 Modelling regular left and right skewed strategies • 302 Modelling tail shocks and structural breaks • 303 Modelling drawdown persistence • 303 Modelling "nothing works" regimes • 303 Importing libraries • 304 Mean reversion strategy • 305 Trend following strategy • 306 Injecting left tail shocks • 309 Drawdown persistence for the trend following strategies • 310 Plotting baseline and individual failure modes • 311 Portfolio level failure • 313 Running a classic asset allocation algorithm ...................................................... 316 Equal weight • 317 Mean–variance optimization • 317 Risk parity • 318 Minimum variance • 320 Maximum diversification • 321 Table of Contents xii
Page 14
Maximum Sharpe ratio • 322 Hierarchical Risk Parity • 323 Backtest all 7 allocation algorithms across 6 strategy pairs • 325 Volatility Is the Wrong Lens • 330 Dynamic Exposure Allocation (DEA) • 331 Layer 1: Strategy Failure Geometry (upper bands) • 332 Layer 2: Portfolio Elasticity Envelope (upper_band_limit) • 332 Layer 3: Risk Oscillator (equity-state dependent) • 333 Layer 4: Temporary boost • 335 Layer 5: Clip exposures • 335 Exposure Allocation Implementation • 335 The podium of asset allocation algorithms • 341 One ring to rule them all: max drawdown tolerance .......................................... 345 Summary ......................................................................................................... 347 Chapter 10: The Trading Journal 349 Technical requirements .................................................................................... 350 The trader's mental software ............................................................................ 350 The six beliefs that cost traders money • 350 The journal as a debugging tool • 351 Two types, one system • 352 The Abraham Wald principle • 353 Making journaling stick • 354 Setting up Airtable ........................................................................................... 354 Creating the TradeLog table • 355 Creating the journal table • 356 Creating the forms • 358 Part A: trade reconciliation ............................................................................... 359 Creating your .env file • 359 Cell 1: setup • 360 Cell 2: Airtable helpers • 361 Cell 3: load_csv • 363 xiii Table of Contents
Page 15
Cell 4: sample data • 363 Cell 5: _seed_portfolio • 364 Cell 6: _split_trades • 365 Cell 7: _write_missed and _write_override • 366 Cell 8: position handlers • 367 Cell 9: reconcile • 369 Cell 10: run • 370 Part B: psychology journal analysis .................................................................... 371 Cell 11: load_journal_session • 371 Cell 12: compute functions • 372 Cell 13: merge and compute • 374 Cell 14: patch to Airtable • 375 Cell 15: summary • 376 AI analysis of the psychology journal ................................................................. 376 Weekly analysis • 376 Kaizen: recurring themes and suggestions • 377 What went well: strengths and reinforcement • 377 Monthly synthesis • 378 Streak recovery • 378 TradeLog analytics ........................................................................................... 378 Maximum adverse excursion • 379 Drawdown analysis • 380 Consecutive loss analysis • 381 Loading the TradeLog records from Airtable • 382 Using the three functions together • 383 Summary ......................................................................................................... 383 Chapter 11: Unlock Access to the Code Bundle and the PDF Version 387 Unlock this book's free benefits in three easy steps ............................................ 388 Table of Contents xiv
Page 16
Other Books You May Enjoy 392 Index 395 xv Table of Contents
Page 17
(This page has no text content)
Page 18
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 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. • • •
Page 19
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, Preface xviii
Page 20
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. • • xix Preface
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List