banner



pair trading strategy python code

Quant-trading

Intro

We'Re right 50.75 percent of the time... but we're 100 percent right 50.75 pct of the time, you can make billions that way.

--- Robert Mercer, co-CEO of Renaissance Technologies

If you trade a lot, you only need to cost right 51 percent of the clip, we need a little edge on each trade.

--- Elwyn Berlekamp, co-Founder of Combinatory Game Hypothesis

The quotes above come from a book by Gregory Zuckerman, a book every quant must read, THE MAN WHO SOLVED THE Food market.

Most scripts inside this depository are technical indicant automated trading. These scripts include respective types of momentum trading, opening range breakout, turn around of financial support danamp; resistance and statistical arbitrage strategies. Yet, quantitative trading is not only about technical analysis. It can refer to procedure finance to exploit first derivative price mismatch, pattern recognition on alternative datasets to generate alphas or low rotational latency order execution in the market microstructure. Hence, thither are a few ongoing projects inside this repository. These projects are mostly quantamental analytic thinking on around fantastic ideas I seed up with to beat the market (or so I thought). In that location is no HFT strategy simply because ultra high frequency information are very pricy to acquire (even consider platforms like Quantopian or Quandl). Additionally, please note that, all scripts are historical data backtesting/forward testing (basically via Python, non C++, perchance Julia in the near future). The Assumption of Mary is that all trades are frictionless. No slippage, nobelium surcharge, atomic number 102 illiquidity. Worst but not least, all scripts contain a global function named independent so that you can plant the scripts directly into you trading system (although too idle to write docstring).

Mesa of Contents

Options Strategy

  • Options Straddle
  • VIX Reckoner

Quantamental Analysis

  • Monte Carlo Project

  • Vegetable oil Money Project

  • Pair Trading

  • Portfolio Optimization Project

  • Smart Farmers Project

  • Wisdom of Crowd Undertaking

Subject Indicators

  • Awesome Oscillator

  • Bollinger Bands Rule Recognition

  • Treble Thrust

  • Heikin-Ashi Candlestick

  • London Breakout

  • MACD Oscillator

  • Parabolic SAR

  • Relative Strength Index Normal Acknowledgment

  • Meteor

Information Source

  • Bloomberg/Eikon

  • CME/LME

  • Histdata/FX Historical Information

  • Macrotrends

  • Stooq/Quandl

  • Reddit WallStreetBets

  • Web Scraping

  • Yahoo Finance/fix_yahoo_finance box/yfinance software


Strategies:

1. MACD oscillator

MACD oscillator is trading scheme 101. MACD refers to Moving Average Convergence/Divergence. It is a momentum trading scheme which holds the belief that upward/downward momentum has more impact connected short term moving normal than long term moving average. Information technology only takes 5 proceedings for whatsoever bloke with nary background in finance to trade in with MACD signals. Regarding the simplicity of MACD oscillator, it is the most common strategy among the non-professionals in the commercialize. In behavioral economics, the more people think in the strategy, the Sir Thomas More efficacious the strategy becomes (not always true, e.g. 2008). Consequently, we should non underestimate the big businessman of MACD oscillator.

For the strategy itself, we cypher prolonged term moving average and short term wriggling average along the close Mary Leontyne Pric of a given stock. To generate the trading signal, we follow up a equivalence between the moving averages of different time horizons. When short term impressive average is above long terminal figure moving normal, we long the given bloodline accordingly. Frailty versa.

Click here to be redirected to the book.

alt text

alt text

2. Pair trading

Pair trading is the basic physique of statistics arbitrage. IT relies on the assumption that ii cointegrated stocks would not drift too far away from for each one other. Eldest footmark, we prize two stocks and run Engle-Granger 2 tone psychoanalysis. At one time the criteria of cointegration is met, we standardize the residual and set one sigma away (two caudate) as the threshold. After that, we reckon the current standardised residual of the selected stocks accordingly. When the standardized residual exceeds the threshold, it generates the trading signal. The simple rule is we always long the cheap stock and short the expensive parentage.

The core idea of pair trading is cointegration. Metaphorically oral presentation, cointegration is like a pair in a clingy relationship where two parties are crazy-glued together. Yet, most relationships break sooner or later, and only the very few toilet make information technology to the marriage (from a statistics view, not being pessimistic). Hence, information technology is important to frequently check on the status quo of cointegration earlier any pair trading gild execution (the indistinguishable applies to relationships).

Click here to be redirected to the handwriting.

alt text

alt text

3. Heikin-Ashi candlestick

Heikin-Ashi, the foreign name in reality referring to 'Average Bar' in Japanese, is an alternative style of candlestick chart. The widely distributed rules of Heiki-Ashi are designed to filtrate taboo the make noise for momentum trading. Hence, Heikin-Ashi shows Thomas More consecutive bars in counterpoint to the standard candle holder, which makes price impulse and overturn points Thomas More distinguishable in figures. Arguably it should outperform the standard candle holder in sideways and choppy markets.

For the scheme itself, initially we make few transformations on quaternity vital benchmarks - Open, Close, Flooding, Low. The next step is to apply unique Heikin-Ashi rules on Heikin-Ashi Open, Immediate, Malodorous, Low to engender trading signals. The downside of Heikin-Ashi (or any momentum trading strategies) is the pokey reaction. Thence, we should put upwards the stop loss position accordingly indeed that we don't get caught up in whatever flash crash.

The rules of Heikin-Ashi can be found in Quantiacs.

Click Here to be redirected to the book.

alt text

alt text

4. London Jailbreak

To one of my pet cities in the international! Proud to glucinium a Londoner!

London Breakout is an intra each day opening range breakout scheme. Basically, information technology is a enchanting information arbitrage across different markets in different time zones. FX securities industry runs 24/7 globally. For instance, you cannot longish the stock of Ford in ASX simply because Gerald Rudolph Ford is listed in Big boar. As FX market is decentralised, you can long any currency mate in any market as long-staple as the market is open. That leaves a door to take a peek at the activity in a squinched foreign FX market before the beginning of domestic FX market.

Back to London Jailbreak, London and Tokyo are two of the largest FX markets in the world. Tokyo FX trading hr is Greenwich Mean Time 0:00 a.m. - GMT 8:59am. London FX trading hour (atomic number 102 summer daylight redeeming) begins at GMT 8:00 a.m. Yet though on that point is an hour of overlap, the crucial timeframe of London Breakout is GMT 7:00 a.m. - GMT 7:59 a.m. a.k.a. the finis trading hour in front the opening of Capital of the United Kingdom grocery store. The price movement of the pivotal timeframe incorporates the info of every last the overnight activities of financial commercialise (from the perspective of the current time zone).

For the strategy itself, we establish upper and take down thresholds anterior to the high and low of the life-or-death timeframe. Erstwhile London FX market opens, we spend the first couple of minutes to check if the price would infract the preset boundaries. If information technology is preceding limen, we long the currency pair consequently. Vice versa. Nevertheless, we should put together a limit to prevent us from trading in the case of irregular opening excitableness. Normally, we clear our positions based connected our target give up loss or stop lucre respectively. By the end of the trading time of day (still from the perspective of the ongoing prison term zone), if there are any open positions, we clear them out.

Detent here to be redirected to the script.

alt text

alt text

5. Awesome oscillator

Awesome oscillator is an upgraded version of MACD oscillator. It is one of those momentum strategies focusing on the halting of moving average. Instead of pickings simple whirling modal on stuffy price, awesome poignant average is derived from the mean of high and blue price. Similar to MACD oscillator, IT takes both half-length full term and long term moving averages to construct the oscillator.

There are various strategies for awful oscillator to beget signals, so much arsenic traditional moving average divergence, twin peaks and saucer. Match peaks is just one of the many names of arse W pattern. The traffic pattern recognition will be covered in another chapter so the important focus of this chapter is dish aerial. Dish aerial is slenderly more complex to implement than the traditional divergence. In return, saucer has the tycoo to beat the slow reaction of the traditionalistic divergence. By and large speaking, a faster response may sound awesome, just it does not guarantee a less risky resultant or a more profitable outcome. Hence, we will take MACD oscillator as a hold group, to examination if amazing oscillator can actually outstrip MACD oscillator.

The rules of impressive oscillator could be found in TradingView.

Click present to be redirected to the script.

alt text

alt text

alt text

alt text

6. Oil Money visualise

This jut is divine by an article on oil-backed unnaturalised central. Amid the bullish expectation for rock oil, the currency convert of oil producing countries would also saltation back. Does this statement really handle?

Accordant to the article past Bloomberg (operating theatre many other similar research), researchers analyse the correlation between petrocurrency and oil color price, instead of the causality. Simply correlation does not up to causality. Correlation could be a coincidence of a math game. We simply cannot draw the conclusion that oil toll moves the currency. Some researchers even use bootstrapping which greatly destroys the autocorrelation of a time series. Thus, IT is vital to give academic psychoanalysis and computer pretending happening some petrocurrencies to test the causality of vegetable oil.

For more details, please pertain to the read me page of a separate directory or quant trading section on my personal blog.

alt text

7. Dual Thrust

If you search dual thrust on google, you will end up with results of rocket engine. Don't panic yet, you backside rest assured that dual thrust strategy is nowhere virtually rocket science. It is just an opening range breakout strategy developed past the give of Universal Specialized Systems. The math convoluted in this strategy is merely primary school level.

Initially we establish upper and frown thresholds settled on former days' open, close, high and low-pitched. When the market opens and the price exceeds certain thresholds, we would learn foresightful/short positions prior to upper/lower thresholds. The scheme is quite useful in intra daily trading. However, in that respect is No stop loss/profit emplacement in this strategy. We reverse our positions when the cost goes from one threshold to the other. We need to clear all positions aside the end of the day.

Rules of double jabbing can personify found in QuantConnect.

Click here to cost redirected to the script.

alt text

8. Rounded SAR

Parabolic SAR is an indicator to identify stop and reversion of a vogue. Usually, Rounded SAR is conferred every bit dotted line either above or below the price in charts. When the Leontyne Price is an uptrend, SAR curve would sit below the price. When the price is downtrend, SAR wind would rise preceding the price. Parabolic SAR is ever considered as a symbol of underground to the Mary Leontyne Pric impulse. When SAR curve and the price curve cross over, it is when trade orders are supposititious to be executed.

The edifice of this strategy seems identical sword-shaped, but the construction of the indicant is exceedingly painful overdue to the involvement of recursive calculation. Illustration connected how to compute Parabolic SAR can be found in Wikipedia but it is not first-rate explained. To get a clear estimation of the computation, my in the flesh testimonial is to take a look at the spreadsheet made by joeu2004.

It is worthy mentioning that SAR and RSI (which will be featured in a later chapter) shares the same founder, Welles Wilder. The rib is a real legend who utilised to work equally mechanical engineer and real demesne developer and later o became a technical psychoanalyst. His book on branch of knowledge trading scheme is a mustiness-read for anyone that wants to lift quant trading organization to the next storey.

Click here to be redirected to the hand.

alt text

9. Bollinger Bands Design Acknowledgement

Bollinger Bands is a real simpleton but compelling index number. There are three bands of this index number. The mid banding is the moving average on the price serial publication (usually takes 20 lags). The amphetamine and lower bands are deuce road standard deviations away from the mid band. Bollinger Bands can be used to test for various types of strategies.

For excitableness trading, muscle contraction and elaboration of the band breadth are crucial elements. Any crisp momentum clustering (information technology behind spring of either up or downwards) would resolution in a Bollinger Bands expansion. And the oscillation in a horizontal channel would result in a Bollinger Bands contraction.

For momentum trading, the phenomenon of 'walk-to the band' indicates the resistance and support level of the underlying asset. In a strong trend, the price perpetually attempts to touch or break through the upper/lower band along with Bollinger Bands wriggling towards the same direction.

For pattern recognition, Bollinger Bands has the potentiality of testing bottom W, top M, head-shoulder patterns, etc. With upper and let down bands served Eastern Samoa an interval, it is easier to identify the hidden pattern in the historical data.

More inside information of Bollinger Bands can atomic number 4 found in TradingView.

Click Here to be redirected to the handwriting.

alt text

10. Relative Forcefulness Index Formula Recognition

RSI (Relative Strength Indicant) is likewise a popular indicator. It reflects the current strength/weakness of the stock price momentum. The deliberation is pretty straight forward. We use 14 days of smoothed rolling average (operating room other flowing average methods) to separately calculate the intra daily uptrend and downtrend. We announce uptrend moving average divided by downtrend moving average as the relative strength. We normalize the relative strength aside 100 which becomes an index called RSI. It is commonly believed that RSI above 70 is overbought and RSI below 30 is oversold. This is the simplest way to trade on RSI (as shown in the pictures at a lower place). Nonetheless, there could be divergence between RSI momentum and price momentum which will non be covered in the hand. The effectiveness of whatsoever divergence strategy on RSI is rather debatable.

alt text

alt text

If you are looking something slightly more complex, well, we can apply radiation diagram recognition proficiency to RSI As well. Unlike strategy None.9 Bollinger Bands, we can immediately look at the patterns of RSI itself instead of the price. Since we have tested three-fold bottom pattern in Bollinger Bands, we would quiz promontory-shoulder pattern on RSI this time.

For inside information of head-shoulder figure, delight refer to Investopedia.

Click Here to be redirected to the hand.

alt text

alt text

11. Monte Carlo project

Monte Carlo, my forward thought on these two row is the terrific casino, where you meet Famke Janssen in tuxedo and introduce yourself, 'Bond, James Bond'. Indeed, the simulation is named after the ill-famed casino. It actually refers to the electronic computer pretending of massive quantity of random events. This unconventional mathematical method is highly powerful in the study of stochastic process.

Here comes the argument on Linkedin that caught my eyes the other Clarence Day. "Stemm price lavatory be seemed as a Wiener Process. Hence, we can economic consumption Three-card monte Carlo pretence to presage the carry price." aforesaid a data science blog. Well, in order of magnitude to cost a Wiener Process, we have to assume the stock price is continuous eventually. In reality, the grocery store closes. The long volatility exists. But that is not the biggest release here. The biggest issue is, can we really use Three-card monte Carlo simulation to predict the stock damage, even a range or its direction?

For more details, please cite to the scan me page of a secern directory operating room quant trading section happening my personal blog.

alt text

12. Options Straddle

Hera marks the introduction of options strategy in this monument. Straddle refers to the build of compasses in the final payment diagram of the strategy. A long-dated straddle involves buying a call option and a put alternative at the same strike price, the same expiration date and preferably the same price. In reality, the same price is non always feasible (telephone call options price high implies higher upside risk, vice versa). It is advisable to trade when the price disparity between prognosticate and arrange options is converging.

Long straddle is commonly seen in consequence driven strategy, e.g. political referendum, company earning give up. It profits from the uncertainty of both-side risk. For upside take a chanc, the potential profit is outright. The expected loss does not come from the downside risk (there is limited gain from downside risk). Instead, it comes from the stagnant price due to insufficient volatility. Therein case, half-length span is more suitable for sideways choppy market.

The crucial element of options straddle is the selection of the strike down Leontyne Price. Every bit the price of options contains the market consensus, the only way to maximize the net profit is to find the optimal strike price to shrink the deprivation bandwidth. This is where the economists kick up in and offer up base case outlook plus best/last scenarios. In contrast to the vernacular misunderstanding of quantitative trading, Option Greeks are no silverish bullet. Amount concerted with fundamental in indefinite, indeed-called quantamental, makes the portfolio impeccable.

Get through here to be redirected to the handwriting.

alt text

13. Portfolio Optimization project

Modern portfolio possibility was introduced in 1952 by Nobelist Harry Markowitz. It is part of investment year 101. Merely I watched a video past Wolfram recently. IT challenged the traditional approach and introduced graph theory to asset diversification. There are plenitude of quant shops deploying fancy mathematic tools to solve the grocery store. The real question for us is, as fancy as it sounds, does graph theory work on portfolio optimization?

alt text

This project is documented in the repository of Chart Theory. For more inside information, delight refer to the read me page of a fork directory or graph theory section on my syntactic category blog.

14. Smart Farmers picture

I know a lot of you have complained that this repository isn't quantitative enough. You are yelling for the ultimate weapon of math devastation such as Poisson process or Jensen's inequality. Well, the object of quantitative trading is roiled out to a greater extent 💶 rather than deploying an elegant closed form par. If you crave for good dispute in mathematics, you are always welcome to check out my Graph Theory repository. Even so, I think the birth of this project bequeath meet your picky demand. Buon appetito 😋

🍊 🍍 🍈 🌽 and 🍠 are something we let been taking for granted. Up until COVID-19, we finally fall to senses that farmers are one of our depressed-prepaid essential workers. This project is ordained to the optimal allocation of agricultural resources. Past trading agricultural market, we are able to eliminate the inefficiency in the crop commercialize. Ideally no food will be wasted and farmers will constitute fairly compensated.

The project as such intends to leverage convex optimization to gauge farmers' plantation planning for different crops. Presumptuous farmers are Homo Economicus, their end game is to maximize the turn a profit regarding the price impact from issue and demand. Their decision is affected by arable land area and biological features of crops. We develop this smart model accordingly to acquire a head start in trading 🍚 and 🍫

alt text

For Sir Thomas More details, please refer to the read me Sri Frederick Handley Page of a split up directory or quant trading part on my personal blog.

15. VIX Calculator

VIX is the fear gauge of Sdanamp;P 500 exponent. By victimization Riemann aggregate and Taylor serial expansion, we are able to convert a continuous fair price variance swap to a separate options volatility index, which is called VIX. VIX is determined past two components, 3-calendar week-ahead every week Sdanamp;P 500 options and one-month-ahead monthly Sdanamp;P 500 options. It is de facto market awaited volatility of SdanAMP;P 500 index in 30 days. So far it has been practical to more or less stock convert indices and some forex pairs. Since VIX is such a great risk direction tool, why don't we apply information technology to any plus with options sign on? The objective of this script is to create a VIX calculator for whatever commodity options within some given duration of forecast time horizon.

alt text

Click Hera to be redirected to the script.

16. Sapience of Crowds Project

Every now and then, we read some bulge brackets hit the headline, "XXX will reach 99999€ in 20YY". More or less forecasts hit the bull's eye only most projections are as accurate as astrology. Price prediction can personify easily influenced past the cognitive bias. In the commercial enterprise market, there is deservingness to the idea that consensus guess is the best oracle. Past harnessing the power of supporting players learning, we are about to purchase Dawid-Skene framework and Platt-Burges model to eliminate the single noise tie in with each individual judgement. The end gamy is to reveal the underlying constitutional value generated by the collective noesis of research analysts from different investment banks. Is wisdom of crowds a crystal ball for trading?

alt text

This project is documented in the repository of Car Learning. For more inside information, please refer to the read me page of a fork directory or machine learning segment on my personal web log.

17. Shooting Whiz

Can we guess that airplanes in the night pitch are like shot stars? I could rattling practice a wish correct nowadays!

--- Hayley Williams, Lead Vocalist of Paramore

Shooting star, such a poetic advert, is merely a simple candlestick model. It has a long upper shadow, little lower shadow and a wee real body, which resonates the SHAPE of a shooting star. Similar to a real comet, shot virtuoso is a luckless signal. Information technology indicates the beginning of a pessimistic momentum after a price uptrend. However, the definition of a shooting star in mathematics is sophisticated. Not umpteen candlesticks can suffice the nonmoving criteria of shot hotshot. In practice, people relax the constraint on shooting star ready to trigger the impressive.

A sibling of shooting star is known as hammer which is in effect a vertical flipped shooting star with optimistic outlook. The close toll of a hammer is suppositional to be higher than the undisguised price. Another sibling of shooting star is named inverted pound. Inverted hammer shares the same shape with shot star, only inverted hammer comes with higher close price than open cost and usually is an omen of Mary Leontyne Pric hike. Nonetheless, there is nobelium "inverted shot star". As malicious as it sounds, the official name is called hanging man...

Click here to be redirected to the script.

alt text


STAY TUNED

pair trading strategy python code

Source: https://github.com/je-suis-tm/quant-trading

Posted by: andersonhunisgung.blogspot.com

0 Response to "pair trading strategy python code"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel