High-Pass Filter (HP)

Parameters: period = 48

Overview

The High Pass Filter strips away long term trend components from price data to reveal the underlying cycles and oscillations that drive short term market behavior, functioning like a mathematical microscope that magnifies rapid price changes while suppressing gradual directional drift. By applying a single pole infinite impulse response algorithm, the filter passes high frequency movements above its cutoff period while attenuating lower frequencies, effectively detrending the price series to oscillate around zero. Positive filtered values indicate price momentum exceeds what the trend alone would predict, suggesting acceleration or overextension, while negative values reveal deceleration or price lagging behind trend expectations. Traders leverage high pass filtered data to identify cycle bottoms and tops within trending markets, as the detrended output clearly shows when short term oscillations reach extremes regardless of the underlying trend direction. The period parameter acts as a frequency gate, with shorter periods preserving more price movement detail but also more noise, while longer periods create smoother oscillations that better isolate dominant market cycles. Cycle analysts particularly value this filter for extracting pure cyclical components from trending markets, enabling precise timing of entries and exits based on the natural rhythm of price oscillations rather than absolute price levels.

Implementation Examples

Get started with High‑Pass in a few lines:

use vectorta::indicators::moving_averages::highpass::{highpass, HighPassInput, HighPassParams};
use vectorta::utilities::data_loader::{Candles, read_candles_from_csv};

// Using with a price slice
let prices = vec![100.0, 102.0, 101.5, 103.0, 105.0, 104.5];
let params = HighPassParams { period: Some(48) };
let input = HighPassInput::from_slice(&prices, params);
let result = highpass(&input)?;

// Using with Candles (defaults: source="close", period=48)
let candles: Candles = read_candles_from_csv("data/sample.csv")?;
let input = HighPassInput::with_default_candles(&candles);
let result = highpass(&input)?;

// Access the filter values
for v in result.values { println!("HP: {}", v); }

API Reference

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

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

// From candles with default params (close, period=48)
HighPassInput::with_default_candles(&Candles) -> HighPassInput
Parameters Structure
#[derive(Debug, Clone, Copy)]
pub struct HighPassParams {
    pub period: Option<usize>, // Default: 48
}
Output Structure
pub struct HighPassOutput {
    pub values: Vec<f64>, // Detrended values (high‑pass output)
}
Validation, Warmup & NaNs
  • period > 0 and period ≤ len(data); datasets with len ≤ 2 are invalid.
  • Requires at least one finite value; if all are NaNHighPassError::AllValuesNaN.
  • Must have at least period data points after the first finite value; otherwise HighPassError::NotEnoughValidData.
  • cos(2π/period) ≈ 0 (e.g., period = 4) → HighPassError::InvalidAlpha.
  • No warmup prefix: outputs start at index 0 with y[0] = x[0]; leading NaNs propagate.
Error Handling
use vectorta::indicators::moving_averages::highpass::{highpass, HighPassError};

match highpass(&input) {
    Ok(output) => process(output.values),
    Err(HighPassError::EmptyInputData) => println!("Input is empty"),
    Err(HighPassError::AllValuesNaN) => println!("All values are NaN"),
    Err(HighPassError::InvalidPeriod { period, data_len }) =>
        println!("Invalid period {} for data length {}", period, data_len),
    Err(HighPassError::NotEnoughValidData { needed, valid }) =>
        println!("Need {} points after first finite, only {} available", needed, valid),
    Err(HighPassError::InvalidAlpha { .. }) =>
        println!("Alpha computation invalid (period near singularity)"),
    Err(HighPassError::InvalidKernel) => println!("Invalid batch kernel"),
}

Python Bindings

Basic Usage

High‑Pass filter functions with optional kernel selection:

from vectorta import highpass, highpass_batch, HighPassStream
import numpy as np

prices = np.array([100.0, 102.0, 101.5, 103.0, 105.0, 104.5], dtype=np.float64)

# Single run
hp = highpass(data=prices, period=48, kernel=None)  # returns np.ndarray (float64)

# Streaming
stream = HighPassStream(48)
for p in prices:
    v = stream.update(float(p))

# Batch sweep
out = highpass_batch(data=prices, period_range=(10, 60, 5), kernel=None)
vals = out['values']   # shape: [num_combos, len(prices)]
periods = out['periods']
CUDA Acceleration

CUDA helpers for batch and many‑series processing (when built with CUDA):

from vectorta import highpass_cuda_batch_dev, highpass_cuda_many_series_one_param_dev
import numpy as np

# One series, many parameters (device array result)
prices_f32 = np.asarray(prices, dtype=np.float32)
dev_arr = highpass_cuda_batch_dev(data_f32=prices_f32, period_range=(10, 60, 5), device_id=0)

# Many series, one parameter set (time‑major [T, N])
tm = np.random.rand(1000, 64).astype(np.float32)
dev_arr2 = highpass_cuda_many_series_one_param_dev(data_tm_f32=tm, period=48, device_id=0)

JavaScript/WASM Bindings

Basic Usage

Calculate High‑Pass in JavaScript/TypeScript:

import { highpass_js } from 'vectorta-wasm';

const prices = new Float64Array([100.0, 102.0, 101.5, 103.0, 105.0, 104.5]);
const hp = highpass_js(prices, 48);
console.log('HP values:', hp);
Memory‑Efficient Operations

Zero‑copy operations for large datasets:

import { highpass_alloc, highpass_free, highpass_into, memory } from 'vectorta-wasm';

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

const inPtr = highpass_alloc(n);
const outPtr = highpass_alloc(n);

new Float64Array(memory.buffer, inPtr, n).set(prices);
highpass_into(inPtr, outPtr, n, 48);
const hp = new Float64Array(memory.buffer, outPtr, n).slice();

highpass_free(inPtr, n);
highpass_free(outPtr, n);
Batch Processing

Test multiple period values efficiently:

import { highpass_batch_js, highpass_batch_metadata_js } from 'vectorta-wasm';

const prices = new Float64Array([/* historical prices */]);
const start = 10, end = 60, step = 5;

const meta = highpass_batch_metadata_js(start, end, step); // periods tested
const combos = meta.length;

const flat = highpass_batch_js(prices, start, end, step);
const rows = combos, cols = prices.length;
const matrix: number[][] = [];
for (let r = 0; r < rows; r++) {
  const s = r * cols; matrix.push(flat.slice(s, s + cols));
}

Performance Analysis

Comparison:
View:
Loading chart...

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

Related Indicators