Algorithmic Short Selling with Python
eBook - ePub

Algorithmic Short Selling with Python

Refine your algorithmic trading edge, consistently generate investment ideas, and build a robust long/short product

Laurent Bernut, Michael Covel

Share book
  1. 376 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Algorithmic Short Selling with Python

Refine your algorithmic trading edge, consistently generate investment ideas, and build a robust long/short product

Laurent Bernut, Michael Covel

Book details
Book preview
Table of contents
Citations

About This Book

Leverage Python source code to revolutionize your short selling strategy and to consistently make profits in bull, bear, and sideways marketsKey Features• Understand techniques such as trend following, mean reversion, position sizing, and risk management in a short-selling context• Implement Python source code to explore and develop your own investment strategy• Test your trading strategies to limit risk and increase profitsBook DescriptionIf you are in the long/short business, learning how to sell short is not a choice. Short selling is the key to raising assets under management. This book will help you demystify and hone the short selling craft, providing Python source code to construct a robust long/short portfolio. It discusses fundamental and advanced trading concepts from the perspective of a veteran short seller. This book will take you on a journey from an idea ("buy bullish stocks, sell bearish ones") to becoming part of the elite club of long/short hedge fund algorithmic traders. You'll explore key concepts such as trading psychology, trading edge, regime definition, signal processing, position sizing, risk management, and asset allocation, one obstacle at a time. Along the way, you'll will discover simple methods to consistently generate investment ideas, and consider variables that impact returns, volatility, and overall attractiveness of returns. By the end of this book, you'll not only become familiar with some of the most sophisticated concepts in capital markets, but also have Python source code to construct a long/short product that investors are bound to find attractive.What you will learn• Develop the mindset required to win the infinite, complex, random game called the stock market• Demystify short selling in order to generate alpa in bull, bear, and sideways markets• Generate ideas consistently on both sides of the portfolio• Implement Python source code to engineer a statistically robust trading edge• Develop superior risk management habits• Build a long/short product that investors will find appealingWho this book is forThis is a book by a practitioner for practitioners. It is designed to benefit a wide range of people, including long/short market participants, quantitative participants, proprietary traders, commodity trading advisors, retail investors (pro retailers, students, and retail quants), and long-only investors.At least 2 years of active trading experience, intermediate-level experience of the Python programming language, and basic mathematical literacy (basic statistics and algebra) are expected.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Algorithmic Short Selling with Python an online PDF/ePUB?
Yes, you can access Algorithmic Short Selling with Python by Laurent Bernut, Michael Covel in PDF and/or ePUB format, as well as other popular books in Business & Investments & Securities. We have over one million books available in our catalogue for you to explore.

Information

Year
2021
ISBN
9781801810395
Edition
1

5

Regime Definition

During the Napoleonic wars, field surgeons with limited resources had to make quick decisions as to whom would need surgery, who could survive without, and the unfortunate ones for whom nothing could be done. Triage was born out of necessity to allocate limited time and resources in the most efficient and humane way possible. In the stock market, regime is another word for triage. Some are bullish, some are bearish, and some are inconclusive.
Markets tend to "stay wrong" a lot longer than investors tend to stick with you. Segregating stocks into different regime buckets—triaging them—before performing in-depth analysis is an efficient allocation of resources. The objective of this initial triage is not to predict where stocks could, would, or should be headed, but to practice the long-lost art of actively listening to what the market has to say.
Some market participants like to spend time and resources on building bear theses for stocks that stubbornly defy the gravity of reason. This is not efficient for two reasons. First, they expect reversion to the mean. On the long side, they trade trends and ride outperformers, expecting them to continue to do well. Meanwhile, on the short side, they trade mean reversion and expect expensive stocks to choke on humble pie and come back down to cheap prices again.
As we will analyze in the coming chapters, trend following and mean reversion have opposite pay-offs and risk profiles. Long trend-following and short mean-reversion does not reduce risk. It compounds it. For now, it suffices to say that market participants must make a choice. Either they trade trends expecting them to develop, or inefficiencies expecting them to correct. When they choose to trade both trends and inefficiencies, their investment style is incongruent. They invite the worst outcome of each style, which unsurprisingly tends to happen simultaneously at the worst time.
Secondly, expecting stocks to revert is essentially like trying to time the top. It is like standing in the middle of the tracks expecting freight train after freight train to stop. Bull regimes tend to outlast investors' patience for gallantry. It is more prudent to wait for more information to surface and the tide to turn bearish before placing a short.
As a different approach, establishing a market regime is something that could really help fundamental short-sellers. They often show up too early. They place their bets long before the broader market starts to factor in the information. The difference between a short selling guru and the dreaded tap on the shoulder is 6 months. Short internet stocks in 1999, and you'll be teaching math to bored university students in 2000. Short the same stocks as early as late January 2000, and a new short selling star is born.
In the following sections, we will look at various regime definition methods, before comparing them:
  • Importing libraries
  • Creating a charting function
  • Breakout/breakdown
  • Moving averages
  • Higher highs/higher lows
  • Floor/ceiling
  • Methodology comparison
  • Let the market regime dictate the best strategy
You can access color versions of all images in this chapter via the following link: https://static.packt-cdn.com/downloads/9781801815192_ColorImages.pdf. You can also access source code for this chapter via the book's GitHub repository: https://github.com/PacktPublishing/Algorithmic-Short-Selling-with-Python-Published-by-Packt

Importing libraries

For this chapter and the rest of the book, we will be working with the pandas, numpy, yfinance, and matplotlib libraries. We will also be working with find_peaks from the ScientificPython library.
So, please remember to import them first:
# Import Libraries import pandas as pd import numpy as np import yfinance as yf %matplotlib inline import matplotlib.pyplot as plt from scipy.signal import find_peaks 

Creating a charting function

Before we visually compare various regime methods, let's publish the source code for a colorful charting function called graph_regime_combo. The parameters will gradually make sense as we unveil each method.
The code is as digestible as Japanese mochi rice, a common cause of death by asphyxiation for toddlers, elderly people, and foreigners, like the author, in Japan. The structure is however simple, like the author as well. Everything depends on whether the floor/ceiling method is instantiated in the rg variable, or not. If floor/ceiling is present, then it supersedes everything else. If not, the other two methods (breakout and moving average crossover) are printed. The ax1.fill_between method identifies the boundaries. Read all of them to understand the conditions. The rest is uneventful:
#### Graph Regimes #### def graph_regime_combo(ticker,df,_c,rg,lo,hi,slo,shi,clg,flr,rg_ch, ma_st,ma_mt,ma_lt,lt_lo,lt_hi,st_lo,st_hi): '''  https://www.color-hex.com/color-names.html  ticker,df,_c: _c is closing price  rg: regime -1/0/1 using floor/ceiling method  lo,hi: small, noisy highs/lows  slo,shi: swing lows/highs  clg,flr: ceiling/floor  rg_ch: regime change base  ma_st,ma_mt,ma_lt: moving averages ST/MT/LT  lt_lo,lt_hi: range breakout High/Low LT   st_lo,st_hi: range breakout High/Low ST   ''' fig = plt.figure(figsize=(20,8)) ax1 = plt.subplot2grid((1,1), (0,0)) date = df.index close = df[_c] ax1.plot_date(df.index, close,'-', color='k', label=ticker.upper()) try: if pd.notnull(rg): base = df[rg_ch] regime = df[rg] #### removed for brevity: check GitHub repo for full code #### for label in ax1.xaxis.get_ticklabels(): label.set_rotation(45) ax1.grid(True) ax1.xaxis.label.set_color('k') ax1.yaxis.label.set_color('k') plt.xlabel('Date') plt.ylabel(str.upper(ticker) + ' Price') plt.title(str.upper(ticker)) plt.legend() #### Graph Regimes Combo #### 
Now that this deadly code is out of the way, survivors may proceed to the next stage: range breakout.

Breakout/breakdown

"Kites rise highest against the wind—not with it."
– Winston Churchill
This is the oldest and simplest trend-following method. It works for both bull and bear markets. If the price makes a new high over x number of periods, the regime is bullish. If the price makes a fresh low over x number of periods, the regime is bearish. This method is computationally easy to implement.
Popular durations are 252 tradin...

Table of contents