Systemicalpha

Value Clamp

systemic:core-clampMathfunction1 cr

Inputs

NameTypeDescription
Min ValuefloatThe **Min Value** sets the floor for your data. Any input value below this threshold is raised to exactly this value.
Max ValuefloatThe **Max Value** sets the ceiling for your data. Any input value above this threshold is lowered to exactly this value.
DatafloatarrayThe **Data** input accepts any numeric series you want to constrain within boundaries. This could be raw price data, indicator outputs, returns, or any calculated values that may occasionally produce extreme outliers.

Outputs

NameTypeDescription
ClampfloatarrayThe CLAMP module produces a single output series containing the bounded values.

In the chaos of financial markets, boundaries save portfolios. The May 6, 2010 Flash Crash saw the Dow Jones plunge nearly 1,000 points in minutes—a cascading failure partly caused by algorithms responding to extreme signals without limits. The Clamp module is your first line of defense: a simple yet powerful tool that enforces hard boundaries on any data series, preventing extreme values from propagating through your trading system.

Whether you're building a position sizing algorithm, preprocessing data for machine learning, or creating a signal that must stay within safe operating limits, CLAMP ensures that no matter how wild the input, the output remains controlled and predictable.


The Core Formula

Clamp(x)=max⁡(Min,  min⁡(x,  Max))\text{Clamp}(x) = \max\bigl(\text{Min},\; \min(x,\; \text{Max})\bigr)

Equivalently expressed as a piecewise function:

Clamp(x)={Minif x<Minxif Min≤x≤MaxMaxif x>Max\text{Clamp}(x) = \begin{cases} \text{Min} & \text{if } x < \text{Min} \\[4pt] x & \text{if } \text{Min} \leq x \leq \text{Max} \\[4pt] \text{Max} & \text{if } x > \text{Max} \end{cases}

In plain English: Values below the minimum get raised to the minimum. Values above the maximum get lowered to the maximum. Everything in between passes through unchanged.


How Clamping Works

flowchart TD
    INPUT["Input Value: x"] --> CHECK{"Where is x?"}
    
    CHECK -->|"x < Min"| FLOOR["Output = Min<br/>🔺 Raised to floor"]
    CHECK -->|"Min ≤ x ≤ Max"| PASS["Output = x<br/>✓ Unchanged"]
    CHECK -->|"x > Max"| CEIL["Output = Max<br/>🔻 Lowered to ceiling"]
    
    FLOOR --> OUT["Bounded Output"]
    PASS --> OUT
    CEIL --> OUT
    
    style FLOOR fill:#dc2626,color:#fff
    style PASS fill:#059669,color:#fff
    style CEIL fill:#2563eb,color:#fff
    style OUT fill:#6b7280,color:#fff

Worked Example

Original ValueMin = 10Max = 50Clamped ResultAction
5105010Raised to floor
20105020Unchanged
35105035Unchanged
55105050Lowered to ceiling
-100105010Raised to floor

The Distribution Effect

Clamping transforms the tails of a distribution by "folding" extreme values onto the boundaries:

flowchart LR
    subgraph Before["Raw Distribution"]
        B1["Fat tails extend<br/>to extreme values"]
        B2["Outliers present"]
    end
    
    subgraph Transform["CLAMP Applied"]
        T["Values outside [Min, Max]<br/>compressed to boundaries"]
    end
    
    subgraph After["Clamped Distribution"]
        A1["Bounded range"]
        A2["Spikes at boundaries<br/>(if many outliers)"]
    end
    
    Before --> Transform --> After

Important: Clamping is not normalization—it doesn't redistribute values proportionally. It's a hard cutoff that can create "pileups" at the boundaries if many values exceed the limits.


Real-World Applications

1. The Circuit Breaker: Preventing Algorithmic Runaway

One of the most critical applications of clamping is preventing trading algorithms from generating extreme positions during market stress:

flowchart TD
    subgraph Signal["Raw Signal Generation"]
        SIG["Momentum Signal<br/>Range: -∞ to +∞"]
    end
    
    subgraph Safety["Safety Layer"]
        CLAMP["CLAMP<br/>Min: -100%, Max: +100%"]
    end
    
    subgraph Position["Position Sizing"]
        POS["Position = Signal × Capital"]
    end
    
    subgraph Risk["Risk Outcome"]
        SAFE["Maximum exposure<br/>= 100% of capital"]
    end
    
    SIG --> CLAMP --> POS --> SAFE

Scenario: Your momentum signal typically ranges from -50 to +50. During a flash crash, it suddenly spikes to +500 (indicating extreme buying pressure on the rebound). Without clamping, your position size calculation might try to buy 500% of your capital—a catastrophic overleveraging event.

With CLAMP: The signal is capped at +100, limiting your maximum position to a manageable size regardless of how extreme the underlying signal becomes.

2. Z-Score Winsorization for Machine Learning

When feeding financial data into machine learning models, outliers can dominate model training and lead to poor generalization. Clamping Z-scores is a common preprocessing technique:

Z-Score RangeStatistical InterpretationAction
Beyond ±3σOccurs in ~0.3% of normal dataClamp to ±3
Between ±2σ and ±3σOccurs in ~4.6% of dataKeep or clamp to ±2.5
Within ±2σ95% of normal dataPass through

Why ±3? In a normal distribution, 99.7% of values fall within 3 standard deviations. Values beyond this threshold are often considered outliers that may distort analysis.

3. Return Capping for Risk Models

Extreme daily returns can blow up Value-at-Risk (VaR) calculations. Many institutional risk models clamp returns before computing risk metrics:

Asset ClassTypical Daily Return RangeSuggested Clamp
Large-cap equities-5% to +5%±10%
Cryptocurrencies-20% to +20%±30%
Forex majors-2% to +2%±5%
Commodities-5% to +5%±15%

Clamping returns at these levels captures the vast majority of real price action while preventing once-in-a-decade events from dominating your risk calculations.

4. Indicator Rescaling

Some indicators (like RSI) are already bounded 0-100, but others have no natural limits. Clamping creates consistent ranges for multi-indicator systems:

flowchart LR
    subgraph Unbounded["Unbounded Indicators"]
        ZS["Z-Score: -∞ to +∞"]
        ROC["Rate of Change: -∞ to +∞"]
        MOM["Momentum: -∞ to +∞"]
    end
    
    subgraph Clamp["CLAMP Layer"]
        C1["CLAMP(-3, +3)"]
        C2["CLAMP(-50, +50)"]
        C3["CLAMP(-100, +100)"]
    end
    
    subgraph Uniform["Bounded Range"]
        B1["Comparable scales"]
        B2["Safe for combination"]
    end
    
    ZS --> C1 --> B1
    ROC --> C2 --> B1
    MOM --> C3 --> B1

Choosing Your Boundaries

The art of clamping lies in setting appropriate boundaries. Too tight, and you lose valuable signal information. Too loose, and the clamp provides no protection.

Statistical Approaches

MethodFormulaWhen to Use
Fixed percentileClamp at 1st and 99th percentileRobust to distribution shape
Standard deviationMean ± k×σ (k=2 or 3)Assumes near-normal distribution
Domain knowledgeSet by market expertiseWhen you know the realistic limits
Regulatory/risk limitsExternally mandatedCompliance requirements

Dynamic vs Static Clamping

ApproachDescriptionTrade-off
Static CLAMPFixed Min/Max valuesSimple, predictable, may become stale
Dynamic CLAMPRecalculate bounds periodicallyAdapts to market conditions, more complex

For dynamic clamping, consider connecting the Min/Max inputs to rolling percentile or standard deviation calculations.


CLAMP vs Alternative Normalization Methods

MethodHow It WorksBest For
CLAMPHard cutoff at boundariesSafety limits, preventing extremes
PERC (Percentile)Rank-based position in historyAdaptive thresholds, distribution-free
ZSCR (Z-Score)Distance from mean in std devsStandardization, outlier detection
Min-Max ScalingRescale to [0,1] rangeFull range transformation
flowchart TD
    Q["What do you need?"] --> SAFE{"Prevent extreme values<br/>from exceeding limits?"}
    SAFE -->|Yes| CLAMP["Use CLAMP"]
    SAFE -->|No| COMPARE{"Compare current value<br/>to recent history?"}
    COMPARE -->|Yes| PERC["Use PERC"]
    COMPARE -->|No| STANDARD{"Need standardized<br/>units (std devs)?"}
    STANDARD -->|Yes| ZSCR["Use ZSCR"]
    STANDARD -->|No| BOTH["Consider combining<br/>ZSCR + CLAMP"]

Edge Cases and Considerations

SituationBehavior
Min > MaxInvalid configuration—ensure Min ≤ Max
All values within rangeAll values pass through unchanged
All values outside rangeAll values clamped to nearest boundary
Missing (null) valuesOutput is null at the same position—never clamped to a boundary
Infinite valuesClamped to the nearest boundary like any other number
Min = MaxAll values become that single value

Missing Data

When an input value is missing (null)—a data gap or a closed-market slot—the output is null at that exact position. CLAMP never fakes the math: a missing value is not treated as 0.0 and is never pushed to the Min or Max boundary. Every real number, however extreme (including infinities), has a valid clamped result, so CLAMP has no "invalid input" case—only missing inputs produce null outputs.

In live execution, CLAMP returns exactly one datapoint: the newest value, which is null when that slot is missing.

Information Loss Warning

Clamping discards information about how extreme outliers were. If distinguishing between "moderately extreme" and "catastrophically extreme" matters to your analysis, consider using CLAMP alongside the original series rather than as a replacement.


The "Guardrails" Pattern: A Complete Example

Combine clamping with other modules to create a robust signal processing pipeline:

flowchart TD
    subgraph Data["Raw Data"]
        PRICE["Price Series"]
    end
    
    subgraph Signal["Signal Generation"]
        MOM["Momentum(20)"]
    end
    
    subgraph Normalize["Normalization"]
        ZSCR["Z-Score(50)"]
    end
    
    subgraph Guardrails["Safety Guardrails"]
        CLAMP["CLAMP(-3, +3)"]
    end
    
    subgraph Action["Trade Logic"]
        GTR["If > +2"]
        LST["If < -2"]
    end
    
    subgraph Trades["Actions"]
        BUY["Consider Long"]
        SELL["Consider Short"]
    end
    
    PRICE --> MOM --> ZSCR --> CLAMP
    CLAMP --> GTR --> BUY
    CLAMP --> LST --> SELL

This pattern:

  1. Calculates raw momentum
  2. Standardizes with Z-score (tells you how unusual the momentum is)
  3. Clamps to ±3 (prevents extreme Z-scores from dominating)
  4. Generates signals based on the bounded, standardized values

Advantages

AdvantageDescription
PredictabilityOutput range is guaranteed—no surprises
Computational efficiencyO(n) single-pass operation
SimplicityEasy to understand, debug, and explain
Safety netPrevents cascading failures from extreme inputs
ComposableWorks well in data processing pipelines

Limitations

LimitationMitigation
Information lossKeep original series for reference if needed
Arbitrary boundariesUse statistical methods to set bounds
Not adaptiveConnect to rolling statistics for dynamic bounds
Boundary pileupIf too many values hit limits, reconsider your bounds

Further Reading

Rendering diagrams...
© 2026 WanoLabs. All rights reservedAlpha build v0.1.5