Implementing a CMO Mean-Reversion State Machine in Python
A rule such as “exit after five bars” sounds unambiguous until you have to decide which event starts the clock.
This tutorial turns a Chande Momentum Oscillator (CMO) mean-reversion rule into an explicit state machine. The interesting part is not the indicator formula. It is preserving the intended event order when entry thresholds, timer resets, and two independent exit routes interact.
By the end, you should be able to:
distinguish an indicator condition from a position state; model a timer that resets while a position is open; identify boundary and bar-timing choices that change program behavior.
- Define the Indicator Before the Strategy
CMO compares the magnitude of recent upward and downward close-to-close changes:
CMO = 100 × (sum of gains − sum of losses) ÷ (sum of gains + sum of losses)
A positive result means gains dominated the selected window. A negative result means losses dominated it. The output normally falls between −100 and +100.
Here is a compact implementation for a series of closing prices:
def cmo(closes, period=9): changes = closes.diff() gains = changes.clip(lower=0) losses = -changes.clip(upper=0)
gain_sum = gains.rolling(period).sum()
loss_sum = losses.rolling(period).sum()
denominator = gain_sum + loss_sum
return 100 * (gain_sum - loss_sum) / denominator
Production code should define what happens when the denominator is zero and should not evaluate strategy rules until the rolling window is ready.
CMO is descriptive rather than predictive. A value below −50 only means losses dominated the current window strongly enough to cross that boundary. It does not establish that the next price change must be positive. Figure 1: CMO compares gains and losses over a rolling window; it does not estimate reversal probability.
- Convert the Written Rules Into States
The rule set is long only:
Calculate CMO over nine bars. Open a long position when CMO is strictly below −50. Close the position when CMO is strictly above +50. Otherwise, close it when five bars have passed since the latest bar where CMO was below −50.
The state required to implement this is small:
position_open = False last_low_cmo_bar = None
The boolean answers whether position-management rules should run. The index stores the most recent qualifying low-CMO event.
Keeping these concepts separate prevents a common mistake: treating every reading below −50 as a new entry while a position is already open.
- Preserve the Event Order
A minimal update function can be written as:
def update_state(state, bar_index, cmo_value): if not state.position_open: if cmo_value < -50: state.position_open = True state.last_low_cmo_bar = bar_index return "open" return None
if cmo_value < -50:
state.last_low_cmo_bar = bar_index
momentum_exit = cmo_value > 50
timed_exit = (
state.last_low_cmo_bar is not None
and bar_index - state.last_low_cmo_bar >= 5
)
if momentum_exit or timed_exit:
state.position_open = False
state.last_low_cmo_bar = None
return "close"
return None
The sequence matters. While the position is open, the latest low-CMO index is updated before the timer is evaluated. A new reading below −50 therefore resets the clock on that bar.
- The Timer Is Not a Fixed Holding Period
Consider the following synthetic sequence:
Bar 0: CMO falls below −50 and opens the state. Bar 1: CMO remains below −50, so the timer anchor moves to Bar 1. Bar 2: CMO remains below −50, moving the anchor again. Bar 3 onward: CMO rises above −50 but remains below +50.
The five-bar count begins from Bar 2, not Bar 0. If CMO falls below −50 again later, the anchor moves forward again.
That behavior is different from storing an entry index and closing when:
bar_index - entry_bar >= 5
Both versions are valid programs, but they represent different algorithms. Naming the variable last_low_cmo_bar instead of entry_bar makes the intended state easier to review. Figure 2: The timer restarts whenever a new CMO reading below −50 appears.
- Strict Boundaries Are Part of the API
The entry comparison is cmo_value < -50, not <= -50. A value of exactly −50 does not open the state.
The recovery comparison is cmo_value > 50, not >= 50. A value of exactly +50 does not close it through the momentum route.
Boundary behavior belongs in tests:
def test_boundaries(): assert entry_signal(-50.0) is False assert entry_signal(-50.01) is True assert recovery_exit(50.0) is False assert recovery_exit(50.01) is True
These tests are more useful than comments such as “enter around −50,” because they preserve the exact contract.
- Test the Reset Behavior Directly
The timer logic deserves its own test rather than being inferred from a full simulation:
def test_low_cmo_reading_resets_timer(state): update_state(state, 0, -55) # open; anchor = 0 update_state(state, 1, -52) # anchor = 1 update_state(state, 2, -51) # anchor = 2
assert update_state(state, 6, -10) is None
assert update_state(state, 7, -10) == "close"
At Bar 6, only four bars have passed since the latest qualifying condition. At Bar 7, five have passed.
Additional tests should cover:
CMO crossing above +50 before the timeout; another low-CMO reading immediately before timeout; missing or duplicated bars; indicator warm-up; repeated calls for the same completed bar; an attempted entry while the position is already open.
- Separate Signal Time From Execution Time
The state model above assumes one update per completed bar. It does not define when an external order is filled.
A real application should keep at least three events distinct:
The bar becomes final. The strategy produces an open or close intent. An execution layer accepts, rejects, or fills that intent.
If a signal is calculated from a completed bar, using that same bar’s earlier price as the fill introduces a timing inconsistency. The strategy state and order state should also remain separate so that a rejected or partially filled order does not silently become a confirmed position.
- Change One Parameter at a Time
The CMO period, thresholds, and timeout affect different parts of the program:
Changing the period recalculates the indicator series. Changing the entry threshold changes which existing values qualify. Changing the timeout changes the state transition after a low-CMO event.
Changing all three together may create a new configuration, but it makes debugging difficult because multiple causes change simultaneously.
For implementation testing, parameterize the functions and verify invariants before examining any market-specific behavior. Figure 3: Changing the period recalculates the series; changing a threshold only moves the comparison line.
Implementation Checklist
Before considering the state machine complete, verify:
the rolling indicator is warmed up; signals use completed bars; comparisons are strictly < -50 and > 50; a low-CMO reading resets the timer while already open; the timer is anchored to the latest qualifying condition; only one long state can be active; signal state and order state are not conflated; missing and duplicate bars have defined behavior.
Main Takeaway
The useful lesson is not “buy when CMO is low.” It is that natural-language timing rules must be converted into named state and tested transition by transition.
In this example, entry_bar and last_low_cmo_bar produce different algorithms. Making that distinction explicit is what turns a vague five-bar exit into reviewable code.
Author note: Prepared with research support from AlgoRover using publicly available strategy materials and documented default parameters. This article explains software behavior for educational purposes and is not individualized investment advice.
About the author
- https://www.algorover.ai/en/
Comments
Join the discussionNo comments yet. Be the first to comment.
Algorithmic Strategy Explained
A practical series that turns public algorithmic trading strategies into clear, testable rule sets. Each article explains the indicators, parameters, execution order, and implementation details, with reproducible examples you can explore and backtest on AlgoRover.io—without performance promises or individualized investment advice.