Momentum (MOM)

Parameters: period = 10

Overview

The Momentum indicator measures the velocity of price changes by calculating the difference between the current price and the price from a specified number of periods ago, providing a raw measure of how fast and in what direction price is moving. This simple calculation of current price minus past price creates an oscillator that swings above and below zero, where positive values indicate upward momentum and negative values signal downward pressure. When momentum peaks and starts declining while price continues higher, it warns of weakening strength behind the move, creating the divergences that traders use to anticipate reversals. The indicator serves dual purposes in trading systems: as a trend following tool when momentum aligns with price direction, and as a contrarian signal when divergences emerge between momentum and price action. Unlike bounded oscillators like RSI, momentum has no fixed limits, making it particularly effective for identifying acceleration phases in strong trends where traditional overbought and oversold levels become meaningless.

Implementation Examples

Get started with MOM in just a few lines:

use vectorta::indicators::mom::{mom, MomInput, MomParams};
use vectorta::utilities::data_loader::{Candles, read_candles_from_csv};

// Using with price data slice
let prices = vec![100.0, 102.0, 101.5, 103.0, 105.0, 104.5];
let params = MomParams { period: Some(10) };
let input = MomInput::from_slice(&prices, params);
let result = mom(&input)?;

// Using with Candles data structure
// Quick start with default parameters (period=10; source="close")
let candles: Candles = read_candles_from_csv("data/sample.csv")?;
let input = MomInput::with_default_candles(&candles);
let result = mom(&input)?;

// Access MOM values
for value in result.values {
    println!("MOM: {}", value);
}

API Reference

Input Methods
// From price slice
MomInput::from_slice(&[f64], MomParams) -> MomInput

// From candles with custom source
MomInput::from_candles(&Candles, &str, MomParams) -> MomInput

// From candles with default params (close price, period=10)
MomInput::with_default_candles(&Candles) -> MomInput
Parameters Structure
pub struct MomParams {
    pub period: Option<usize>, // Default: 10
}
Output Structure
pub struct MomOutput {
    pub values: Vec<f64>, // MOM values (Price_t - Price_{t - period})
}
Validation, Warmup & NaNs
  • Errors: MomError::EmptyInputData, MomError::AllValuesNaN, MomError::InvalidPeriod { period, data_len }, MomError::NotEnoughValidData { needed, valid }.
  • period > 0 and period ≤ data.len(); otherwise InvalidPeriod.
  • Must have at least period valid points after the first finite value; otherwise NotEnoughValidData.
  • Warmup: indices before first + period are NaN (where first is first non-NaN in input).
  • Computation uses value[t] − value[t−period]; NaN inputs propagate to outputs at corresponding indices.
  • Streaming: MomStream::update returns None until the buffer fills for period updates; then returns value − valuet−period.
Error Handling
use vectorta::indicators::mom::{mom, MomError, MomInput, MomParams};

let input = MomInput::from_slice(&prices, MomParams { period: Some(10) });
match mom(&input) {
    Ok(output) => process_results(output.values),
    Err(MomError::EmptyInputData) =>
        eprintln!("Input data is empty"),
    Err(MomError::AllValuesNaN) =>
        eprintln!("All input values are NaN"),
    Err(MomError::InvalidPeriod { period, data_len }) =>
        eprintln!("Invalid period {} for data length {}", period, data_len),
    Err(MomError::NotEnoughValidData { needed, valid }) =>
        eprintln!("Need {} valid data points after first finite, only {}", needed, valid),
}

Python Bindings

Basic Usage

Calculate MOM using NumPy arrays (default: period=10):

import numpy as np
from vectorta import mom

# Prepare price data as NumPy array
prices = np.array([100.0, 102.0, 101.5, 103.0, 105.0, 104.5])

# Calculate MOM with defaults (period=10)
result = mom(prices)

# Or specify parameters and kernel
result = mom(prices, period=10, kernel="avx2")

# Result is a NumPy array matching input length
print(f"MOM values: {result}")
Streaming Real-time Updates

Process real-time price updates efficiently:

from vectorta import MomStream

# Initialize streaming MOM calculator
stream = MomStream(period=10)

# Process real-time price updates
for price in price_feed:
    mom_value = stream.update(price)

    if mom_value is not None:
        # MOM value is ready (None during warmup period)
        print(f"Current MOM: {mom_value}")
Batch Parameter Optimization

Test multiple period values for optimization:

import numpy as np
from vectorta import mom_batch

# Your price data
prices = np.array([...])

# Define period sweep (start, end, step)
period_range = (5, 20, 5)  # 5, 10, 15, 20

# Run batch calculation
results = mom_batch(
    prices,
    period_range=period_range,
    kernel="auto"
)

print(f"Values shape: {results['values'].shape}")  # (num_periods, len(prices))
print(f"Periods tested: {results['periods']}")
CUDA Acceleration

CUDA support for MOM is currently under development. The API will follow the same pattern as other CUDA-enabled indicators.

# Coming soon: CUDA-accelerated MOM calculations
# See APO page for example patterns that new CUDA APIs will follow.

JavaScript/WASM Bindings

Basic Usage

Calculate MOM in JavaScript/TypeScript:

import { mom_js } from 'vectorta-wasm';

// Price data as Float64Array or array
const prices = new Float64Array([100.0, 102.0, 101.5, 103.0, 105.0, 104.5]);

// Calculate MOM with specified period
const result = mom_js(prices, 10);

// Result is a Float64Array (via wasm_bindgen)
console.log('MOM values:', result);

async function calculateMOM(prices: Float64Array): Promise<Float64Array> {
  try {
    return mom_js(prices, 10);
  } catch (error) {
    console.error('MOM calculation failed:', error);
    throw error;
  }
}
Memory-Efficient Operations

Use zero-copy operations for better performance with large datasets:

import { mom_alloc, mom_free, mom_into, memory } from 'vectorta-wasm';

// Prepare your price data
const prices = new Float64Array([/* your data */]);
const length = prices.length;

// Allocate WASM memory for input and output
const inPtr = mom_alloc(length);
const outPtr = mom_alloc(length);

// Copy input data into WASM memory
new Float64Array(memory.buffer, inPtr, length).set(prices);

// Calculate MOM directly into allocated memory
// Args: in_ptr, out_ptr, len, period
mom_into(inPtr, outPtr, length, 10);

// Read results from WASM memory (slice() to copy out)
const momValues = new Float64Array(memory.buffer, outPtr, length).slice();

// Free allocated memory when done
mom_free(inPtr, length);
mom_free(outPtr, length);

console.log('MOM values:', momValues);
Batch Processing

Test multiple period values efficiently:

import { mom_batch_js, mom_batch_into, mom_alloc, mom_free, memory } from 'vectorta-wasm';

// Your price data
const prices = new Float64Array([/* historical prices */]);

// Object-based batch API returning values, combos, rows, cols
const out = mom_batch_js(prices, { period_range: [5, 20, 5] });
// out.values: number[] (flattened), out.combos: { period: number | null }[]
const rows = out.rows; // number of periods tested
const cols = out.cols; // equals prices.length

// Reshape if needed
const matrix = [] as number[][];
for (let r = 0; r < rows; r++) {
  const start = r * cols;
  matrix.push(out.values.slice(start, start + cols));
}

// Zero-copy batch into pre-allocated memory
const inPtr = mom_alloc(prices.length);
new Float64Array(memory.buffer, inPtr, prices.length).set(prices);
// Allocate output for rows * cols
const outPtr = mom_alloc(rows * cols);
// The into API also accepts explicit [start,end,step]
const rows2 = mom_batch_into(inPtr, outPtr, prices.length, 5, 20, 5);
const flatOut = new Float64Array(memory.buffer, outPtr, rows * cols).slice();

mom_free(inPtr, prices.length);
mom_free(outPtr, rows * cols);

Performance Analysis

Comparison:
View:

Across sizes, Rust CPU runs about 2.45× faster than Tulip C in this benchmark.

Loading chart...

AMD Ryzen 9 9950X (CPU) | NVIDIA RTX 4090 (GPU) | Benchmarks: 2026-01-05

Related Indicators