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 find mean reversion stocks? ›

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

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 is the mean reversion bot? ›

The Mean Reversion Bot stands as a testament to the power of data-driven decision-making. By harnessing historical price patterns and leveraging the principle that asset prices tend to revert to their long-term mean, traders can identify and capitalize on potential opportunities.

What is an example of mean reversion trading? ›

For example, if the spread widens beyond its historical range, traders may consider buying the instrument that is relatively cheaper and selling the instrument that is relatively more expensive, with the expectation that the spread will eventually revert back to its mean.

How do you create a mean reversion trading strategy? ›

Data Analysis: Analyse historical data to identify periods when the market demonstrates significant mean reversion tendencies and study price action in several timeframes during those periods. Look for periods when price ranges (reverts to the mean), as these periods can provide you with potential entry points.

What is the AI algorithm for stock trading? ›

AI trading, also known as algorithmic trading, is a method of executing trades in financial markets using computer algorithms. These algorithms analyze vast amounts of data, such as historical price movements, market trends, and economic indicators, to identify patterns and make trading decisions.

How to create AI for trading? ›

The first step in building any trading bot, AI-infused or not, is to define your trading strategy. In other words, this is the set of rules you will implement into the bot. This could include various indicators, for example, RSI, or more complex machine learning models that analyze a variety of market signals.

Which algorithm is best for trading? ›

Below are the best five types of algorithmic trading strategies for Indian markets which you can follow:
  1. Trends and Momentum Following Strategy. ...
  2. Arbitrage Trading Strategy. ...
  3. Mean Reversion Strategy. ...
  4. Weighted Average Price Strategy. ...
  5. Statistical Arbitrage Strategy.
Jan 16, 2024

What is the best mean reversion strategy? ›

A successful mean reversion strategy requires careful selection of financial assets, identifying precise entry and exit points through technical indicators, and a strong risk management framework that includes stop-loss and take-profit levels.

What is the mean reversion portfolio strategy? ›

Mean Reversion is an effective quantitative strategy based on the theory that prices will revert back to its historical mean. A basic example of mean reversion follows the benchmark of Constant Rebalanced Portfolio.

What is the formula for mean reversion speed? ›

Mean reversion speed κ is better interpreted with the concept of half-life, which can be calculated from HL=ln(2)/κ. For example, if the mean reversion coefficient is κ=1.5, then the half-life of the process is ln(2)/1.5=0.46209812 years, or about 6 months.

What is the difference between momentum and mean reversion? ›

Mean reversion strategies centre around stocks reverting to their mean values and capitalising on relative mispricing among stocks. In contrast, momentum strategies focus on stocks that have shown strong recent performance and are expected to continue that trend.

What is the best indicator for mean reversion strategy? ›

Traders often use technical indicators like the Relative Strength Index (RSI) and tools like standard deviation and Bollinger Bands to supplement mean reversion strategies. These indicators help identify oversold or overbought levels and track unusual price movements.

What is the mean reversion of the Nasdaq? ›

The idea that stock prices revert to a long term level. Hence, if there is a shock in prices (unexpected jump, either up or down), prices will return or revert eventually to the level before the shock.

Top Articles
Latest Posts
Article information

Author: Errol Quitzon

Last Updated:

Views: 6178

Rating: 4.9 / 5 (79 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Errol Quitzon

Birthday: 1993-04-02

Address: 70604 Haley Lane, Port Weldonside, TN 99233-0942

Phone: +9665282866296

Job: Product Retail Agent

Hobby: Computer programming, Horseback riding, Hooping, Dance, Ice skating, Backpacking, Rafting

Introduction: My name is Errol Quitzon, I am a fair, cute, fancy, clean, attractive, sparkling, kind person who loves writing and wants to share my knowledge and understanding with you.