v1.0.2

Quant Factors & Risk

Kafal natively provides institutional-grade statistical transformations, execution cost modeling, and portfolio allocation heuristics.

Time-Series & Statistical Factors

These functions operate on rolling windows, applying standard statistical transformations to price or volume series.

// Rolling Z-Score: (x - mean) / std over a 50-bar window
z_val = zscore(close, 50)

// Normalization & Standardization
norm_series = normalize(close, 100)      // Bounds series strictly to [0.0, 1.0]
std_series  = standardize(close, 100)    // Standardizes to mean 0, std 1

// Rolling Relationships
spy_close = request_security("SPY", "1D", "close")
correlation = rolling_corr(close, spy_close, 50)

Cross-Sectional Evaluation

Cross-sectional built-ins evaluate properties globally across the available dataset. These are primarily utilized in research mode via the feature() pipeline.

// Time-series rank normalized to [0.0, 1.0]
percentile_rank = rank(close, ascending=true)

// Winsorization: Clip extreme outliers beyond 3 standard deviations
clipped_close = winsorize(close, z=3.0)

// Assign values into decile buckets (0 to 9)
bucket_idx = decile(close, n=10)

Risk, Cost & Allocation Models

Kafal exposes sophisticated execution cost algorithms based on spread decay, volatility regimes, and dynamic portfolio weighting constraints.

// Dynamic trailing stop calculation
trailing_stop = atr_stop(close, ta.atr(high, low, close, 14), mult=2.0, direction="long")

// Volatility regime classification (0 = Low, 1 = Medium, 2 = High)
regime = vol_regime(ta.atr(high, low, close, 14), lookback=50)

// Total Trade Cost: Aggregates spread, impact %, and commission %
slip_cost = slippage_model(spread=0.02, vol=stdev(close, 20), notional=10000.0)
total_cost = total_trade_cost(price=close, slippage_price=slip_cost, impact_pct=0.05, commission_pct=0.0005)

// Volatility Target Weighting
alloc_weight = vol_target_weight(percent_change(close, 1), target_vol=0.10, lookback=50)