In partnership with

The Free Newsletter Fintech and Finance Execs Actually Read

If you work in fintech or finance, you already have too many tabs open and not enough time.

Fintech Takes is the free newsletter senior leaders actually read. Each week, we break down the trends, deals, and regulatory moves shaping the industry — and explain why they matter — in plain English.

No filler, no PR spin, and no “insights” you already saw on LinkedIn eight times this week. Just clear analysis and the occasional bad joke to make it go down easier.

Get context you can actually use. Subscribe free and see what’s coming before everyone else.

🔔 Limited-Time Holiday Deal: 20% Off Our Complete 2026 Playbook! 🔔

Level up before the year ends!

AlgoEdge Insights: 30+ Python-Powered Trading Strategies – The Complete 2026 Playbook

30+ battle-tested algorithmic trading strategies from the AlgoEdge Insights newsletter – fully coded in Python, backtested, and ready to deploy. Your full arsenal for dominating 2026 markets.

Special Promo: Use code FEBRUARY2026 for 20% off

Valid only until February 25, 2026 — act fast!

👇 Buy Now & Save 👇

Instant access to every strategy we've shared, plus exclusive extras.

— AlgoEdge Insights Team

🔔 Flash Launch Alert: AlgoEdge Colab Vault – Your 2026 Trading Edge! 🔔

The $79 book gives you ideas on paper.
This gives you 20 ready-to-run money machines in Google Colab.

I've turned my 20 must-have, battle-tested Python strategies into fully executable Google Colab notebooks – ready to run in your browser with one click.

One-click notebooks • Real-time data • Bias-free backtests • Interactive charts • OOS tests • CSV exports • Pro metrics

Test on any ticker instantly (SPY, BTC, PLTR, TSLA, etc.).

Launch Deal (ends Feb 28, 2026):
$129 one-time (save $40 – regular $169 after)

Lifetime access + free 2026 updates.

Inside the Vault (20 powerhouses):

  • Bias-Free Cubic Poly Trend

  • 3-State HMM Volatility Filter

  • MACD-RSI Momentum

  • Bollinger Squeeze Breakout

  • Supertrend ATR Rider

  • Ichimoku Cloud

  • VWAP Scalper

  • Donchian Breakout

  • Keltner Reversion

  • RSI Divergence

  • MA Ribbon Filter

  • Kalman Adaptive Trend

  • ARIMA-GARCH Vol Forecast

  • LSTM Predictor

  • Random Forest Regime Classifier

  • Pairs Cointegration

  • Monte Carlo Simulator

  • FinBERT Sentiment

  • Straddle IV Crush

  • Fibonacci Retracement

Special Promo: Use code VAULT2026 for 20% off

Valid only until February 25, 2026 — act fast!

👇 Buy Now & Save 👇
Buy Now – $129

P.S. Run code today → test live tomorrow → outperform the book readers.

Reply “VAULT” for direct link or questions.

Premium Members – Your Full Notebook Is Ready

The complete Google Colab notebook from today’s article (with live data, full Hidden Markov Model, interactive charts, statistics, and one-click CSV export) is waiting for you.

Preview of what you’ll get:

Inside:

  • Installation of the lumibot trading framework

  • Configuration for Alpaca paper trading API credentials

  • Definition of the ExtendedMeanReversionStrategy class

  • Custom RSI calculation function

  • Main trading logic combining MA crossover + RSI filter + 200-day trend filter

  • Position management and order submission (buy/sell 100 shares of TSLA)

  • Backtesting setup using Yahoo Finance data (2022–2026) with option to switch to live trading

Free readers – you already got the full breakdown and visuals in the article. Paid members – you get the actual tool.

Not upgraded yet? Fix that in 10 seconds here👇

Google Collab Notebook With Full Code Is Available In the End Of The Article Behind The Paywall 👇 (For Paid Subs Only)

In my previous article, we explored what the Lumibot framework is. We looked at some basic functions, using a buy-and-hold strategy and comparing its results against the SPY index, we also explored some of its capabilities with a simple example.

For this article, I have planned to use a different trading strategy, the mean reversion strategy, using moving averages as buy and sell indicators. We will briefly review this strategy, its use, and how to implement it in Lumibot. In addition, we will use Alpaca broker to execute our strategy.

Wall Street Just Named the Most Crowded Trades of 2026

AI stocks. Metals. Crypto.

Surprise, surprise; gold crashed 16%. Silver plunged 34%. Bitcoin dropped to 1 year lows.

All supposedly "uncorrelated" assets moving in lockstep largely because of overleveraged margin.

JPM strategists warn that the same leverage is still a risk.

Those markets may be recovering now, but cascading liquidations could trigger quickly across several asset classes simultaneously.

So much for diversifying away risk, right?

But get this–

70,819 everyday investors have allocated $1.3 billion fractionally across 500+ exclusive investments. 

Not real estate or PE… Blue-chip art. Sounds crazy, right?

Now it’s easy to invest in art featuring legends like Banksy, Basquiat, and Picasso, thanks to Masterworks.

They do the heavy lifting from acquisition to sale, so you can diversify with the strategy typically limited to the ultra-wealthy.

(Past sales delivered net returns like 14.6%, 17.6%, and 17.8% on works held longer than a year.)*

*Investing involves risk.  Past performance is not indicative of future returns. Important Reg A disclosures: masterworks.com/cd

Mean Reversion Strategy: What Is?

What is a Mean Reversion? Well, in simple terms, let’s imagine a pendulum swinging. When it deviates too much from the center (the mean), gravity pulls it towards the center, causing a “momentum” that moves the pendulum to the other side, so, translating this in the stock market is a price oscillation, which gives us the entry and exit signals. It is a widely used trading strategy because of its simplicity, also, it is based on statistical indicators such as RSI, and Moving Averages, among others. This strategy can be applied to various financial instruments, including stocks, currencies, and commodities.

The next graph shows a bit better how it works. The red line represents the actual price movements of a stock over time. The sold action is triggered when the 90d moving average crosses the 30d moving average, is because this cross suggests a potential downward trend, so, a sell signal. Conversely, when the 30d moving average crosses the 90d moving average, there is a potential upward trend, so this is a buy signal.

Mean reversion strategy using Moving Averages of 30 and 90D. Credits: Auquan

Components of a Mean Reversion Strategy

Although this strategy is simple in its execution, it is good to know its components:

  • Trend Filter:

Confirm that the overall market (or specific asset) is uptrend. For stocks, this often involves checking if the price is above its 200-day Simple Moving Average (SMA), for instance.

  • Oversold/Overbought Conditions:

Use the SMA to identify potential entry points. For example, you might look for instances where the stock price deviates significantly below a shorter-term SMA, such as the 50-day SMA, to signal an oversold condition.

  • Entry and Exit Rules:

When using SMA indicators, the rules are simple: Buy when the price drops significantly below the 50-day SMA and starts to show signs of reverting back towards the mean (e.g., when it begins to move back towards the 50-day SMA). Sell when the price rebounds and crosses above the 50-day SMA.

In our exercise, we will implement a mean reversion strategy for the Tesla stock (ticker: TSLA) using two moving averages: short-term and long-term moving averages. The rationale behind using moving averages is that they provide a smooth representation of the asset’s price over a specified period, helping to identify potential deviations from the long-term trend.

Will Your Retirement Income Last?

A successful retirement can depend on having a clear plan. Fisher Investments’ The Definitive Guide to Retirement Income can help you calculate your future costs and structure your portfolio to meet your needs. Get the insights you need to help build a durable income strategy for the long term.

Setting up the environment

To get started with Lumibot, we will need to install the library in our environment, just using the command:

pip install lumibot

Our next step will be to get the API Key and the API secret of the ALPACA broker to connect it to Lumibot.

Obtaining the ALPACA API Key and Secret

Before starting coding, we will need our credentials from Alpaca broker, you can open an account here.

After opening your account and logging in, check your home dashboard, go to the API Keys section (red frame on the screenshot below), click on the generate button, you will obtain your API SECRET.

Getting API Key and Secret from Alpaca Broker. Screenshot from Alpaca Broker.

Importing libraries

Let’s start with the code, we will import some methods from lumibot library, also, we will use datetime and numpy to handle dates and make some calculations.

from config import ALPACA_CONFIG
from lumibot.brokers import Alpaca
from lumibot.backtesting import YahooDataBacktesting
from lumibot.strategies import Strategy
from lumibot.traders import Trader
from datetime import datetime
import numpy as np

Among the imported libraries, you can see that there is one in particular called config, well, this is just a module created to save our API-key and API-secret of our alpaca account, here is the body of this script:

ALPACA_CONFIG = {
    "API_KEY": "YOUR_API_KEY",
    "API_SECRET": "YOUR_SECRET_KEY",
    "ENDPOINT": "https://paper-api.alpaca.markets",
    # if you want to go live, use ENDPOINT = https://api.alpaca.markets
}

Then, save it as config.py and put it in your working folder. You can use a different way to store your keys and upload them in your environment, so, just do it the best that fits with you.

Designing our strategies

The next step is to create our .py file for each strategy, so, we are going to start with the Class MeanReversionStrategy, and define the initialize method, with some key parameters, such as the signal for our trading algorithm (“buy” or “sell”, setting the initial status as None) and the windows of ours moving averages, remember that we have to define a short and long terms windows, which are common indicators used in trading strategies, in our case, we will use 20 days for short moving average and 50 for long. Other parameters to explain here are the position_size, which sets the number of shares to trade, and the sleeptime, set to ‘1D’, which means the strategy will check once per day to buy or sell shares.

Here is the code for SMA indicator:

class MeanReversionStrategy(Strategy):
    def initialize(self):
        self.signal = None
        self.start = "2022-01-01"
        self.sleeptime = "1D"
        self.short_window = 5  # Short-term moving average window
        self.long_window = 20  # Long-term moving average window
        self.position_size = 100  # Number of shares to trade

Next, we define the on_trading_iteration method, this will help us to make the calculations around the historical prices,

def on_trading_iteration(self):
    historical_prices = self.get_historical_prices("TSLA", max(self.short_window, self.long_window) * 2, "day")
    stock_data = historical_prices.df
    # Calculate the short-term and long-term moving averages for the closing prices.
    stock_data[f'{self.short_window}-day'] = stock_data['close'].rolling(self.short_window).mean()
    stock_data[f'{self.long_window}-day'] = stock_data['close'].rolling(self.long_window).mean()
    # Generate a 'BUY' signal where the short-term average crosses above the long-term average.
    stock_data['Signal'] = np.where(
        np.logical_and(
            stock_data[f'{self.short_window}-day'] > stock_data[f'{self.long_window}-day'],
            stock_data[f'{self.short_window}-day'].shift(1) < stock_data[f'{self.long_window}-day'].shift(1)
        ), "BUY", None
    )
    # Update the 'Signal' column to 'SELL' where the short-term average crosses below the long-term average.
    stock_data['Signal'] = np.where(
        np.logical_and(
            stock_data[f'{self.short_window}-day'] < stock_data[f'{self.long_window}-day'],
            stock_data[f'{self.short_window}-day'].shift(1) > stock_data[f'{self.long_window}-day'].shift(1)
        ), "SELL", stock_data['Signal']
    )
    
    self. Signal = stock_data.iloc[-1].Signal
    symbol = "TSLA"
    # Execute a 'BUY' order if the signal is 'BUY'.
    if self.signal == 'BUY':
        pos = self.get_position(symbol)
        if pos is not None:
            self.sell_all()
        # Create a 'buy' order for the defined position size.
        order = self.create_order(symbol, self.position_size, "buy")
        self.submit_order(order)
    
    # Execute a 'SELL' order if the signal is 'SELL'.
    elif self.signal == 'SELL':
        # Check if there is an existing position.
        pos = self.get_position(symbol)
        if pos is not None:
            self.sell_all()
        order = self.create_order(symbol, self.position_size, "sell")
        self.submit_order(order)

Key Points on this method:

  • Moving Averages: The strategy uses two moving averages, a short-term and a long-term, to determine the trading signal.

  • Trading Signals: A ‘BUY’ signal is generated when the short-term average crosses above the long-term average, and a ‘SELL’ signal when it crosses below.

  • Trading Execution: Based on the signal, the strategy will either buy or sell the specified position_size of the TSLA stock.

  • Position Management: Before executing a new trade, the strategy checks for any existing positions and sells them if necessary.

Now, execute the strategy using this chunk of code:

if __name__ == "__main__":
real_trade = False # Use True for real trade
if real_trade:
    broker = Alpaca(ALPACA_CONFIG)
    strategy = MeanReversionStrategy(broker=broker)
    trader = Trader()
    trader.add_strategy(strategy)
    trader.run_all()
else:
    start = datetime(2022, 1, 1)
    end = datetime(2024, 5, 1)
    MeanReversionStrategy.backtest(
        YahooDataBacktesting,
        start,
        end
    )
logo

Subscribe to our premium content to read the rest.

Become a paying subscriber to get access to this post and other subscriber-only content.

Upgrade

Keep Reading