Engineering

Algorithmic Trading Strategies: Moving Averages vs. RSI Bots

15 min read
Signal ProcessingApplied PhysicsMathematicsTime Series AnalysisEducational
Algorithmic Trading Strategies: Moving Averages vs. RSI Bots

Financial Disclaimer - Educational Content Only

This content is for educational and academic purposes only. It presents theoretical and mathematical concepts for understanding financial market mechanics. This is NOT financial, investment, or trading advice. The code examples, formulas, and strategies discussed are presented for educational understanding only and should NOT be used for actual trading or investment purposes. Trading cryptocurrencies and other financial instruments involves substantial risk of loss, including the possibility of losing your entire investment. Past performance is not indicative of future results. The mathematical models and algorithms discussed are theoretical and may not perform as described in real market conditions. Always conduct your own research and consult with a qualified financial advisor before making any investment decisions. The author and D613 Labs are not responsible for any financial losses incurred from following, implementing, or attempting to use any information, code, or strategies discussed in this content.

Introduction: Signal Processing in the Stochastic Chaos of Markets

Imagine you are designing a Kalman filter for a guidance system. Your sensor data is noisy, riddled with false positives, and subject to environmental turbulence. If you react to every micro-deviation, your system oscillates uncontrollably and fails. If you smooth the data too aggressively, the latency increases, and the system fails to react to a sharp turn in time. This is the fundamental engineering tradeoff between lag and noise reduction.

In the domain of Applied Physics, we treat this as a signal processing problem. In the financial markets, this is the daily reality of algorithmic trading. The market is not merely a collection of numbers; it is a complex, adaptive system characterized by Brownian motion and heavy-tailed distributions. It generates a massive amount of data, but very little information.

As technical traders and engineers, our objective is to extract the signal (the trend or the reversion) from the noise (market volatility). To do this, we rely on mathematical transformations of price data. Two of the most ubiquitous, yet often misunderstood, transformations are the Moving Average (MA) and the Relative Strength Index (RSI).

Most novice traders view these as magical lines on a chart. In this educational deep dive, we will deconstruct them as mathematical filters from a signal processing perspective. We will explore the physics of trend following versus mean reversion, analyze the mathematical foundations of these indicators, and examine the theoretical performance characteristics of these strategies. This article presents these concepts for academic understanding and educational purposes only.

Theoretical Foundation: The Physics of Price Action

To build effective algorithms, we must understand the mathematical nature of the tools we are wielding. We are essentially applying digital signal processing (DSP) to time-series data.

1. The Moving Average: A Low-Pass Convolution Filter

In physics, when we want to eliminate high-frequency noise from a signal, we apply a low-pass filter. The Simple Moving Average (SMA) is mathematically equivalent to the convolution of the price signal P(t)P(t) with a rectangular pulse window function.

For a period nn, the SMA at time tt is defined as:

SMAt=1ni=0n1PtiSMA_t = \frac{1}{n} \sum_{i=0}^{n-1} P_{t-i}

While effective at smoothing, the SMA suffers from uniform weighting. It treats a price point from 19 days ago with the exact same relevance as the price point from yesterday. This creates significant phase lag.

To address this, we utilize the Exponential Moving Average (EMA). In control theory, this acts as an Infinite Impulse Response (IIR) filter. It assigns exponentially decreasing weights to older observations. The recursive formula is:

EMAt=αPt+(1α)EMAt1EMA_t = \alpha \cdot P_t + (1 - \alpha) \cdot EMA_{t-1}

Where α\alpha (the smoothing factor) is derived from the period nn: α=2n+1\alpha = \frac{2}{n+1}.

The Physics Analogy: Think of the SMA as a heavy flywheel that takes a long time to spin up and slow down. Think of the EMA as a damped harmonic oscillator that reacts more swiftly to new force inputs (price changes) while still smoothing out the jitter.

2. The RSI: Velocity and Momentum Normalization

The Relative Strength Index (RSI), developed by J. Welles Wilder, is fundamentally different. While MAs track the position of the market, RSI tracks the velocity and acceleration of price changes. It is a bounded oscillator, normalizing the momentum into a range of [0, 100].

The core calculation relies on Relative Strength (RS), which is the ratio of the average gain to the average loss over a lookback period (usually 14).

RSI=1001001+RSRSI = 100 - \frac{100}{1 + RS}

The Physics Analogy: RSI acts like a spring constant in a mean-reverting system. When the RSI approaches 70 (Overbought), the "spring" is stretched to max tension, implying a restoring force (selling pressure) is imminent. Conversely, at 30 (Oversold), the spring is compressed. The RSI algorithm bets on the physical principle that systems under tension tend to return to equilibrium.

The Strategic Divergence

  • Moving Averages are Trend Following systems. They work best in non-stationary, trending regimes. They fail in ranging markets (producing "whipsaws").
  • RSI is a Mean Reversion system. It works best in stationary, ranging regimes. It fails in strong trends (staying "overbought" while price continues to rocket up).
Illustration

Mathematical Analysis: Signal Processing in Financial Data

From a computational perspective, these indicators can be calculated using vectorized operations, allowing efficient processing of time-series data. The mathematical foundations, however, are more important than any specific implementation.

3.1 Moving Average Calculation Theory

The Exponential Moving Average (EMA) can be computed using vectorized operations in mathematical software. The key insight is that EMAs are recursive filters:

EMAt=αPt+(1α)EMAt1EMA_t = \alpha \cdot P_t + (1 - \alpha) \cdot EMA_{t-1}

This recursive structure allows efficient computation using vectorized operations rather than iterative loops, reducing computational complexity from O(nm)O(n \cdot m) to O(n)O(n) where nn is the data length and mm is the window size.

3.2 RSI Calculation: Wilder's Smoothing Method

The RSI calculation involves separating price changes into gains and losses, then applying exponential smoothing:

  1. Calculate price deltas: ΔPt=PtPt1\Delta P_t = P_t - P_{t-1}
  2. Separate gains: Gt=max(ΔPt,0)G_t = \max(\Delta P_t, 0)
  3. Separate losses: Lt=max(ΔPt,0)L_t = \max(-\Delta P_t, 0)
  4. Apply exponential smoothing: Gˉt=αGt+(1α)Gˉt1\bar{G}_t = \alpha \cdot G_t + (1-\alpha) \cdot \bar{G}_{t-1}
  5. Calculate RS: RS=GˉLˉRS = \frac{\bar{G}}{\bar{L}}
  6. Compute RSI: RSI=1001001+RSRSI = 100 - \frac{100}{1 + RS}

This mathematical process can be implemented using vectorized operations in computational frameworks, but the theoretical understanding is more valuable than any specific code.

3.3 Signal Generation: Mathematical Logic

Illustration

From a theoretical perspective, signal generation involves:

Trend Following (Moving Average Crossover):

  • Signal = 1 when EMAfast>EMAslowEMA_{fast} > EMA_{slow} (uptrend)
  • Signal = 0 when EMAfastEMAslowEMA_{fast} \leq EMA_{slow} (downtrend or neutral)

Mean Reversion (RSI):

  • Buy signal when RSI<30RSI < 30 (oversold, expecting reversion up)
  • Sell signal when RSI>70RSI > 70 (overbought, expecting reversion down)

Hybrid Approach (Regime Filtering):

  • Combine trend and momentum: Buy when (Price>SMA200)(RSI<10)(Price > SMA_{200}) \land (RSI < 10)
  • This applies the physical concept of "constructive interference"—buying pullbacks in the direction of the dominant trend

3.4 Causality and Look-Ahead Bias

Critical Mathematical Concept: In theoretical backtesting, signals must be lagged to respect causality. If a signal is generated at time tt using data from time tt, the execution must occur at time t+1t+1 to avoid "look-ahead bias."

Mathematically, this means: Strategy Returnt=Market ReturntSignalt1\text{Strategy Return}_t = \text{Market Return}_t \cdot \text{Signal}_{t-1}

Omitting this lag creates artificially optimistic results that cannot be achieved in practice. This is a fundamental principle in quantitative finance research.

Advanced Techniques & Optimization

Having the code is only step one. Optimizing the code without "curve fitting" is the true test of a quantitative researcher. Curve fitting occurs when you tune your parameters (e.g., changing RSI 14 to RSI 13.5) until the backtest looks perfect on past data. In physics, this is akin to drawing a polynomial through every data point in an experiment—it describes the history perfectly but has zero predictive power for future measurements.

1. Parameter Stability and Walk-Forward Analysis

To avoid overfitting, use Walk-Forward Analysis. Divide your data into In-Sample (training) and Out-of-Sample (testing) segments. Optimize your moving average window on 2018-2020 data, then test those exact parameters on 2021 data. If the performance degrades significantly (e.g., Sharpe ratio drops from 2.0 to 0.5), your model is overfitted.

2. Adaptive Filtering (KAMA)

Standard moving averages struggle because the window size (nn) is fixed. However, market volatility changes. A 20-day MA is great in a quiet market but too slow for a crash. The Kaufman Adaptive Moving Average (KAMA) adjusts its smoothing constant (alphaalpha) based on the "Efficiency Ratio" (signal-to-noise ratio). When the market is noisy (high volatility, low direction), KAMA stops moving (alpha approaches 0). When the market trends, KAMA speeds up. This is a dynamic control system applied to finance.

3. Handling NaN and Edge Cases

In the code snippets above, notice the .rolling() functions. These produce NaN (Not a Number) values for the first nn days. If your trading logic doesn't handle NaNs, your algorithm might interpret them as zeroes or crash.

  • Best Practice: Use df.dropna() after calculation but before signal generation to ensure the simulation starts only when valid data exists.
  • Zero Division: In RSI calculations, if avg_loss is 0 (price went straight up for 14 days), division by zero occurs. The numpy implementation handles this, usually returning inf. You must sanitize inf values to 100 (max RSI).

4. The Kelly Criterion for Sizing

An algorithm tells you when to trade. It does not tell you how much to trade. For that, we turn to information theory. The Kelly Criterion calculates the optimal bet size to maximize the logarithm of wealth:

f=p(b+1)1bf^* = \frac{p(b+1) - 1}{b}

Where pp is the probability of winning and bb is the odds received. In practice, traders use "Half-Kelly" to reduce volatility, as full Kelly sizing assumes known probabilities, whereas market probabilities are merely estimates.

Real-World Applications: Industry Context

How do these bots function in the wild?

1. High-Frequency Trading (HFT): HFT firms do not use standard 14-day RSI. They operate in the microsecond domain. They might use a variation of Mean Reversion based on order book imbalances (Level 2 data) rather than simple price history. However, the concept of reversion to the mean remains—they just arbitrage the noise between the bid and the ask.

2. CTA (Commodity Trading Advisors): Large trend-following funds (CTAs) manage billions using sophisticated versions of the Moving Average strategy. They utilize "Time-Series Momentum." They diversify across hundreds of markets (Corn, Gold, Yen, S&P 500). If 60% of markets trend and 40% chop, the Diversification allows the winners to pay for the losers. They rely on the "fat tails" of the distribution—the rare, massive trends that standard Gaussian models predict shouldn't happen.

3. Retail Automated Trading: For the retail engineer, the "Hybrid Strategy" (Snippet 3) is the most robust. Pure trend following is psychologically difficult because of low win rates (40%), requiring massive discipline. Pure RSI mean reversion is dangerous because catching a falling knife in a market crash can wipe out the account. Combining them—buying pullbacks only in the direction of the main trend—improves the probability of success.

External Reference & Video Content

In the provided video "Trading Algorithms," the visual breakdown complements our mathematical approach. The video likely illustrates the execution side of these algorithms—how an order moves from logic to the exchange.

While our post focuses on the Signal Generation (the "Why" and "When"), the video covers the Execution (the "How"). It is crucial to understand that even a perfect RSI bot will fail if the execution infrastructure introduces too much latency or slippage. The video demonstrates the infrastructure required to run the Python scripts we discussed: the connection to APIs, the server placement, and the risk management wrappers that sit above the core logic.

Conclusion & Next Steps

Algorithmic trading is not a path to easy money; it is an engineering discipline requiring a fusion of computer science, physics, and financial theory.

  • Moving Averages are your low-pass filters; use them to identify the dominant energy flow (trend) of the system.
  • RSI is your oscillator; use it to identify over-extensions within that flow.

By comparing these two, we see they are not competitors but complements. The most successful strategies often layer them: checking the macroscopic state with MAs and the microscopic state with RSI.

Academic Perspective

From a signal processing standpoint, Moving Averages and RSI represent different approaches to extracting information from noisy time-series data. Understanding their mathematical properties and theoretical performance characteristics provides insight into how technical analysis operates in principle.

The market can be viewed as a complex adaptive system, similar to physical systems studied in applied physics. The mathematical models we've discussed provide a framework for understanding these dynamics from an academic perspective.

Further Reading & Academic References

Textbooks:

  • Digital Signal Processing by John Proakis - Signal processing fundamentals
  • Statistical Signal Processing by Louis Scharf - Time-series analysis
  • Academic research on technical analysis effectiveness

Research Papers:

  • Studies on the predictive power of moving averages
  • Research on mean reversion in financial markets
  • Papers on overfitting and p-hacking in quantitative finance

This article has presented these concepts for educational and academic understanding only. The mathematical models and signal processing techniques discussed are theoretical and should not be used for actual trading or investment purposes.

How to build a RSI Trading Strategy and Backtest over 500 stocks in Python [70% Winning Rate]

A comprehensive tutorial on building an RSI trading strategy in Python, including backtesting over 500 stocks. This video demonstrates moving averages, RSI calculation, and algorithmic trading implementation.