A Simple Mean Reversion Stock Trading Script in C# (2024)

In the past, I’ve published stories on Medium showing how to write algorithms that trade stocks based on company fundamentals and how to run a technical analysis day trading algorithm in the cloud. Both of those articles assumed that:

  • Python was the language the reader wanted to use.
  • You had access to an Alpaca brokerage account and could therefore use Polygon’s premium data feed.

This meant that those outside the US were out of luck, as you need to be a US citizen to trade with Alpaca. In this article, though, I’ll show an example implementation of a new C# trading script. Because it uses their free paper-trading API, anyone can run it. You‘ll be able to test it out in their paper trading environment, whether or not you have money in an account with them.

This is How I Implemented Benjamin Graham’s Teachings into an Automated Investing strategyTeaching Your Computer to Invest With Python: Commission-Free Automated Investingmedium.com
Build a Day-Trading Algorithm and Run it in the Cloud — For FreeCommission-free trading with Alpaca on a free Google Cloud Platform instance, step-by-step.medium.com

To get access to Alpaca’s free paper trading API, sign up at Alpaca’s website. Once you’ve done that, you should have access to the dashboard, where you can watch the performance and contents of your portfolio change as your algorithms run. For now, you’ll just need to hit the “Generate Keys” button to get started.

Once you’ve got your API keys, we can go ahead and use them to get our code running. I’ll post the code first, then explain what it’s doing below.

We’ll be using the C# SDK for Alpaca’s trade API, which you can install from NuGet. (The SDK is hosted on GitHub and is open source, so feel free to take a look at the underlying code for yourself.)

To connect to the API, we simply create a new REST client, giving it our keys and the API URL. (All of these pieces of info can be taken from the Alpaca dashboard, and you should fill in the REPLACEMEs near the top of the file with your own keys.) Using the REST client, we check Alpaca’s clock and calendar API endpoints to figure out when the market will open and when we’re getting too near to close. (We don’t want to hold the position overnight, so we liquidate the position before close to be safe.)

The trading logic of the algorithm is simple. It looks at data for one symbol — set here to SPY, as an example — and each minute, it checks on its current price and its average price over the last 20 minutes. If the current price is higher than the average, it doesn’t want to hold any position. However, if the current price is lower than average, it wants to allocate a certain percentage of your portfolio to holding shares. It’s following the economic theory of mean reversion, assuming that when the price is below the average, it’s more likely to come back up.

The “scale” variable at the top determines how much of your portfolio goes into the position. You can see exactly how it factors in with this chunk of code:

Decimal avg = bars.Average(item => item.Close); Decimal currentPrice = bars.Last().Close;
Decimal diff = avg - currentPrice;
// ...
Decimal portfolioShare = diff / currentPrice * scale;

The scale is by default set to 200, and if you follow the code above, you’ll see that means that a change of .5% from the 20 minute average would cause 100% of your portfolio to be invested.

I encourage you to play around with the scale and different symbols, and see if you can find a combination that works for you. SPY is used as an example because it has a high trading volume and does not tend to move too dramatically during market hours. I encourage you to try different symbols and scales and see if you can find an edge on any stocks with this approach. If you’d like to augment the code, too, you might practice by extending the algorithm to check the EMA as well and factor that indicator into its purchasing decisions.

Later, I’ll post another article showing how we can use Polygon’s premium data feed to improve this script. If you’re interested in giving that version a try, you’ll need a brokerage account with Alpaca. With a live trading account, you’ll be ready to give the other version a try as well as apply this code to your own trading ideas.

A Simple Mean Reversion Stock Trading Script in C# (2024)

FAQs

How to build a mean reversion trading strategy? ›

In this strategy, traders look for price divergences from the moving average, which can signal potential buy or sell opportunities. When the price of an asset is trading below its moving average, it is considered undervalued, and traders may consider buying the asset as it is likely to revert back to its mean.

How to find mean reversion stocks? ›

Mean reversion formula

To understand and calculate mean reversion, traders need to calculate the mean. The mean is the average price over a given number of data points. On an asset's trading chart, the mean is easily represented by a simple moving average (SMA). The SMA calculates the average price in the price series.

How to write code for stock trading? ›

In this article, we'll explore the process of writing a trading bot in Python, along with some examples to help you get started.
  1. Step 1: Define Your Strategy. ...
  2. Step 2: Connect to a Broker. ...
  3. Step 3: Set Up Your Environment. ...
  4. Step 4: Write Your Trading Algorithm. ...
  5. Step 5: Implement Risk Management. ...
  6. Step 6: Deploy Your Trading Bot.
Feb 25, 2023

Is mean reversion profitable? ›

In general, mean reversion strategies can be profitable when prices deviate significantly from their historical averages, and the expectation is that they will eventually return to average over time.

What is the simple mean reversion strategy? ›

Simple Mean Reversion is a strategy created by Anthony Garner. It is based on the theory that when prices move too far away from the mean, there is a chance of price reversion. The strategy adds simulated buy and sell signals based on the following values: price, two simple moving averages, and zScore.

What is the simple mean reversion model? ›

A mean reversion strategy is a trading strategy in which prices tend to return to the average levels of the stocks. In this trading pattern, the prices seem to move hard and sustain for an extended period of time.

What are the best indicators for mean reversion trading? ›

Mean reversion trading tries to capitalize on extreme changes in the price of a particular security, assuming that it will revert to its previous state. Some technical analysis mean reversion tools include moving averages, the relative strength index (RSI), bollinger bands, and the stochastic oscillator.

What is the mean reversion algorithm? ›

Mean reversion strategy is based on the concept that the high and low prices of an asset are a temporary phenomenon that revert to their mean value (average value) periodically.

What is an example of reversion to the mean? ›

If one selects only the top scoring 10% of the students and gives them a second test on which they again choose randomly on all items, the mean score would again be expected to be close to 50. Thus the mean of these students would "regress" all the way back to the mean of all students who took the original test.

How to create AI for trading? ›

How to Build a Trading Bot?
  1. 1 Selecting a programming language. ...
  2. 2 Choose your trading platform and the asset you want to trade. ...
  3. 3 Selecting the server to build your trading bot. ...
  4. 4 Define your strategy. ...
  5. 5 Integrate with the exchange API. ...
  6. 6 Backtesting your trading bot. ...
  7. 7 Optimizing your trading bot. ...
  8. 8 Forward testing.
Sep 22, 2023

How to create your own algorithm for trading? ›

To develop algorithmic trading techniques, you need to follow these steps and customise each step according to your requirements.
  1. Step 1: Create a Platform. ...
  2. Step 2: Visualise Your Trading Strategy. ...
  3. Step 3: Define the Time Frame and Other Ratios. ...
  4. Step 4: Test the Algorithm Strategies.

Which algorithm is best for trading? ›

Top Five Algo Trading Strategies of 2024
  1. Trends and Momentum Following Strategy. This is one of the most common and best algo strategy for intraday trading. ...
  2. Arbitrage Trading Strategy. ...
  3. Mean Reversion Strategy. ...
  4. Weighted Average Price Strategy. ...
  5. Statistical Arbitrage Strategy.
Jan 16, 2024

What are the limitations of mean reversion? ›

Limitations of the Mean Reversion Theory

First, a return to normal or mean prices is not guaranteed. A significant price change in the market may reflect a new normal on the underlying asset. For instance, a stock may fall because of a significant change in the regulatory environment.

What is the best timeframe for mean reversion? ›

The time frame is extremely important when it comes to mean reversion. Just like various markets, each time frame has its own way of moving. In fact, I have discovered over the years that the 10 and 20 exponential moving averages work the best on the four hour and daily time frames.

What is the best moving average for reversal? ›

A 20-day moving average will provide many more reversal signals than a 100-day moving average. A moving average can be any length: 15, 28, 89, etc. Adjusting the moving average so it provides more accurate signals on historical data may help create better future signals.

What is the mean reversion strategy using RSI? ›

10-Period RSI Mean Reversion

For this strategy, traders typically set the RSI to a 10-period setting and establish overbought and oversold limits at 80 and 20, respectively. By focusing on shorter intervals, this strategy aims to capture quick reversals in price.

Top Articles
Latest Posts
Article information

Author: Edwin Metz

Last Updated:

Views: 6165

Rating: 4.8 / 5 (78 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Edwin Metz

Birthday: 1997-04-16

Address: 51593 Leanne Light, Kuphalmouth, DE 50012-5183

Phone: +639107620957

Job: Corporate Banking Technician

Hobby: Reading, scrapbook, role-playing games, Fishing, Fishing, Scuba diving, Beekeeping

Introduction: My name is Edwin Metz, I am a fair, energetic, helpful, brave, outstanding, nice, helpful person who loves writing and wants to share my knowledge and understanding with you.