Pairs trading strategy

Using correlation to select two stocks for pairs trading is then invalid, because you are dealing with two time series — which could be diverging from each other, but which could yet have a high correlation. The correct measure of a long-term mean-reverting relationship between two time series should be co-integration. That is why I apply ADF. If we reject the Null-Hypothesis Non-Stationary it means that the two series are co-integrated. I would probably be more conservative and go for stocks within one sector for example energy or banking maybe across different exchanges or countries.

Thank you Walter, I agree that it is safer to choose stocks from the same sector. Amazon and Microsoft appear to be co-integrated too! Save my name, email, and website in this browser for the next time I comment. We have started a series of articles on tips and tricks for data scientists mainly in Python and R. This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Pair Selection

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings. If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again. Home Hacks Tips Contact About. Example of Pairs Trading. George Pipis January 3, 6 min read. Introduction Statistical arbitrage trading is a quantitative and computational approach to equity trading which is widely applied by hedge funds to produce market-neutral returns.

Get the Stock Prices We will work in R and we will get the stock prices using the quantmod package. Close", "", names closePrices head closePrices Construct the Pairs The aim of this strategy is to construct a portfolio of two stocks that are in long-run equilibrium. Our approach will be: Split the data into train and test datasets. As a train dataset, we consider the first observations and as a test dataset the remaining last 32 observations.

We take the logarithm of the closing prices. Notice that we chose to run the regression without an intercept coefficient. This is not necessary since both approaches are correct. We apply the ADF test in order to detect the co-integrated pairs. The strategy is the following: When the spread is above 0. Conclusion Pairs trading is a strategy that can be applied in both bearish and bullish markets.

Share This Post. Share on facebook. Share on linkedin. Share on twitter. Share on email. This will simplify the calculations we will be making to determine our entry later on. For now, we've overwritten the price to zero. That way we can do some simple error checking to make sure the WebSocket is working before checking for trades.


  • how much does a full time forex trader make.
  • option trading using open interest.
  • Pairs Trading - Strategy Deployment Guide?
  • fundamental analysis forex tutorial?

Next we do our spread calculations. The first step is converting the entire DataFrame to show daily percentage changes. Lastly, we take the maximum absolute divergence over the last 20 days and save it as a variable. Note that we've removed the last line of the DataFrame so that the incomplete data is not included in our spread calculation. If we plot the spread, we can see that it does resemble a stationary time-series. Lastly, before jumping into the next section of our code, we run a quick check to see if the WebSocket has started updating prices.

If the WebSocket is updating prices, we can move on and see if the current divergence is greater than the maximum divergence that we calculated. The same method as before can be used to check the spread. If the current absolute spread is larger than the maximum divergence determined earlier on, we can enter into a trade.

Before entering into a trade, we need to determine the correct position size for each asset and also calculate our take profit and stop loss.

Algorithmic Trading Strategies: Pair Trading & Mean Reversion Strategies

We will discuss these aspects in more detail later in the article. Otherwise, the script will sleep for 1 second and return to the start of the loop to continue monitoring for an entry. There is also a quick check here to see if the market is still open. If the market is closed, we can break out of this part and return to the start of the main loop.

Pairs trading

Recall that the first line calls our custom function that puts the script to sleep until the next market open. We move on to the final section of the script that handles what to do once a trade gets taken. Here we check to see our running PnL and exit the trade if either the stop loss or take profit gets hit. Once again, we have an IF statement to check and make sure the market is still open. If not, it will break out and restart from the top and go to sleep until the next market open.

When positioning in a pairs trade, both sides of the trade should be equally weighted in dollars. If both assets had the same price that would be straight-forward. We derive this by taking the amount we want to invest and dividing it by the share price. There are other ways to size positions, depending on your strategy. One alternative is to size positions based on the Beta of the stock. The idea here is that if the Beta between two stocks is different, it would make sense to have a larger weight in the lower Beta stock and smaller weight in the higher Beta stock.

Another approach is targeting the maximum potential loss. That means we can use our full account size on our long leg and rely on leverage to fund the short leg. Lastly, position sizes can be based on correlation.

How To Setup A Pairs Trade On TradingView 👍

If you have two stocks that move similarly, but one stock consistently outperforms the other as an example, the weighting can be adjusted to manipulate the spread into a stationary time-series. In pairs trading, we can't set a static stop loss or take profit. In that case, our gain on one stock would offset the loss on the other which is no reason to exit. To track our PnL, we will continue to monitor incoming WebSocket data and use the following formula to calculate our PnL.

That means if the result of the above equation is positive, we are in profit.

Pairs trade

If it is negative, we have a loss. We hope this article has inspired you to look at developing your own pairs trading strategy. If you're looking for tips on designing your pairs trading strategy, the following link has a lot of useful information- Pairs Trading - A Real-World Guide. It goes into more detail about which asset types work best, different methods to assign weights to your pairs, and also discusses certain things to avoid to help you in your strategy creation.

The full strategy which this tutorial referenced can be found on the following GitHub repository:. AlgoTrading is an Investopedia-recommended online algorithmic trading course with over 30, members. Our aim is to provide the necessary mental models, trading knowledge and quantitative skills to succeed as a trader. Commission-Free trading means that there are no commission charges for Alpaca self-directed individual cash brokerage accounts that trade U.

Technology and services are offered by AlpacaDB, Inc. You can find us AlpacaHQ , if you use twitter. I'm passionate about the markets and programming. My market analysis has been published by many of the top financial websites and I've posted several how-to programming guides at AlgoTrading The second article in our series where we will continue writing out features for our iPhone app - Raven.

This article shows you how to get to the economic data to build a trading algorithm. Here we use monthly unemployment figures. You've successfully subscribed to Alpaca Resources. Next, complete checkout for full access to Alpaca Resources. Welcome back! You've successfully signed in.

Your account is fully activated, you now have access to all content. Your billing info is updated.


  • Pairs Trading Basics: Correlation, Cointegration And Strategy;
  • a forex broker.
  • forex trading game 4 beginners.
  • Complexity!

Billing info update failed.