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

Partager le livre
  1. 376 pages
  2. English
  3. ePUB (adapté aux mobiles)
  4. Disponible sur iOS et 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

DĂ©tails du livre
Aperçu du livre
Table des matiĂšres
Citations

À propos de ce livre

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.

Foire aux questions

Comment puis-je résilier mon abonnement ?
Il vous suffit de vous rendre dans la section compte dans paramĂštres et de cliquer sur « RĂ©silier l’abonnement ». C’est aussi simple que cela ! Une fois que vous aurez rĂ©siliĂ© votre abonnement, il restera actif pour le reste de la pĂ©riode pour laquelle vous avez payĂ©. DĂ©couvrez-en plus ici.
Puis-je / comment puis-je télécharger des livres ?
Pour le moment, tous nos livres en format ePub adaptĂ©s aux mobiles peuvent ĂȘtre tĂ©lĂ©chargĂ©s via l’application. La plupart de nos PDF sont Ă©galement disponibles en tĂ©lĂ©chargement et les autres seront tĂ©lĂ©chargeables trĂšs prochainement. DĂ©couvrez-en plus ici.
Quelle est la différence entre les formules tarifaires ?
Les deux abonnements vous donnent un accĂšs complet Ă  la bibliothĂšque et Ă  toutes les fonctionnalitĂ©s de Perlego. Les seules diffĂ©rences sont les tarifs ainsi que la pĂ©riode d’abonnement : avec l’abonnement annuel, vous Ă©conomiserez environ 30 % par rapport Ă  12 mois d’abonnement mensuel.
Qu’est-ce que Perlego ?
Nous sommes un service d’abonnement Ă  des ouvrages universitaires en ligne, oĂč vous pouvez accĂ©der Ă  toute une bibliothĂšque pour un prix infĂ©rieur Ă  celui d’un seul livre par mois. Avec plus d’un million de livres sur plus de 1 000 sujets, nous avons ce qu’il vous faut ! DĂ©couvrez-en plus ici.
Prenez-vous en charge la synthÚse vocale ?
Recherchez le symbole Écouter sur votre prochain livre pour voir si vous pouvez l’écouter. L’outil Écouter lit le texte Ă  haute voix pour vous, en surlignant le passage qui est en cours de lecture. Vous pouvez le mettre sur pause, l’accĂ©lĂ©rer ou le ralentir. DĂ©couvrez-en plus ici.
Est-ce que Algorithmic Short Selling with Python est un PDF/ePUB en ligne ?
Oui, vous pouvez accĂ©der Ă  Algorithmic Short Selling with Python par Laurent Bernut, Michael Covel en format PDF et/ou ePUB ainsi qu’à d’autres livres populaires dans Business et Investments & Securities. Nous disposons de plus d’un million d’ouvrages Ă  dĂ©couvrir dans notre catalogue.

Informations

Année
2021
ISBN
9781801810395
Édition
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 des matiĂšres