Documentation: Rust - Python | Repository: GitHub
Kand: Blazingly Fast Technical Analysis Library in Rust, Python
Why Kand?
-
🚀 Blazing Fast Built in Rust for elite performance and safety, rivaling top libraries like TALib.
-
🔥 GIL-Free Unlocks Python’s GIL for seamless multi-threading—unlike TALib’s single-threaded limits.
-
⏱️ O(1) Incremental Speed Lightning-fast incremental updates, outpacing traditional batch methods.
-
⚡️ Zero-Copy Native NumPy integration with zero-copy data passing—no overhead, just speed.
-
🛠️ One-Line Install Skip TALib’s complex C library setup—install with a single command.
-
đź’» Cross-Platform Runs effortlessly on macOS, Linux, and Windows.
Discover more benefits in our comprehensive documentation.
Python API
The Python interface of kand
leverages PyO3 for ultra-low latency bindings (~7ns overhead) to the Rust core, seamlessly integrating with NumPy for zero-copy operations and true thread-safe calculations. Below are examples for batch and incremental usage.
import numpy as np
from kand import ema
# Batch EMA computation with zero-copy NumPy integration
# Input: NumPy array of prices (float64)
# Output: Array of EMA values based on period and default smoothing factor
prices = np.array([10.0, 11.0, 12.0, 13.0, 14.0], dtype=np.float64)
ema_values = ema(prices, period=3) # Uses default smoothing factor k=2/(period+1)
# Incremental EMA update for streaming data
# Input: New price and previous EMA; constant-time update
prev_ema = 13.5
new_price = 15.0
new_ema = ema_incremental(new_price, prev_ema, period=3) # Default k=2/(period+1)
Key Features:
- Zero-Copy: Operates directly on NumPy arrays, avoiding memory duplication.
- GIL-Free: Rust backend releases the Python GIL, enabling parallel execution.
- Incremental Updates: O(1) complexity for real-time applications.
Rust API
The Rust interface in kand
provides a high-performance, type-safe implementation of EMA with flexible parameter control. It supports both Vec and ndarray inputs for batch and incremental calculations, as shown below.
use kand::ohlcv::ema;
use ndarray::Array1;
// Batch EMA calculation over a price series
// Input: Price vector, period, optional smoothing factor (None for default k=2/(period+1))
// Output: Writes EMA values to a pre-allocated buffer
let prices = vec![10.0, 11.0, 12.0, 13.0, 14.0];
let mut ema_values = vec![0.0; prices.len()];
ema::ema(&prices, 3, None, &mut ema_values)?; // Default k=2/(4)=0.5
// Batch EMA with ndarray for scientific workflows
let prices = Array1::from_vec(vec![10.0, 11.0, 12.0, 13.0, 14.0]);
let mut ema_values = Array1::zeros(prices.len());
ema::ema(&prices, 3, None, &mut ema_values)?; // Default k=2/(4)=0.5
// Constant-time incremental EMA update
// Input: New price, previous EMA, period, optional smoothing factor
let prev_ema = 13.5;
let new_price = 15.0;
let new_ema = ema::ema_incremental(new_price, prev_ema, 3, None)?; // Default k=0.5
Key Features:
- Memory Efficiency: Leverages mutable buffers (
&mut Vec<f64>
or&mut Array1<f64>
) to store results, slashing memory allocations. - Error Handling: Returns
Result<(), KandError>
orResult<f64, KandError>
for reliable failure detection (e.g., invalid period, NaN inputs). - Incremental Design: O(1) updates tailored for real-time systems.
Setup
Python
Get started with Kand in one command - no extra configuration needed:
Rust
You can take latest release from crates.io
, or if you want to use the latest features / performance improvements point to the main
branch of this repo.
Recommend Rust version >=1.80
.
Functions List
OHLCV Based
- AD - Chaikin A/D Line
- ADOSC - Chaikin A/D Oscillator
- ADR - Average Daily Range [Untested]
- ADX - Average Directional Movement Index
- ADXR - Average Directional Movement Index Rating
- APO - Absolute Price Oscillator
- AROON - Aroon
- AROONOSC - Aroon Oscillator
- ATR - Average True Range
- BBANDS - Bollinger Bands
- BOP - Balance Of Power
- CCI - Commodity Channel Index
- CDL_DOJI - Doji
- CDL_DRAGONFLY_DOJI - Dragonfly Doji
- CDL_GRAVESTONE_DOJI - Gravestone Doji
- CDL_HAMMER - Hammer
- CDL_INVERTED_HAMMER - Inverted Hammer
- CDL_LONG_LOWER_SHADOW - Long Lower Shadow
- CDL_LONG_UPPER_SHADOW - Long Upper Shadow
- CDL_MARUBOZU - Marubozu
- CMO - Chande Momentum Oscillator
- DEMA - Double Exponential Moving Average
- DX - Directional Movement Index
- EMA - Exponential Moving Average
- ECL - Expanded Camarilla Levels [Untested]
- HA - Heikin Ashi Chart
- HT_DCPERIOD - Hilbert Transform - Dominant Cycle Period
- HT_DCPHASE - Hilbert Transform - Dominant Cycle Phase
- HT_PHASOR - Hilbert Transform - Phasor Components
- HT_SINE - Hilbert Transform - SineWave
- HT_TRENDLINE - Hilbert Transform - Instantaneous Trendline
- HT_TRENDMODE - Hilbert Transform - Trend vs Cycle Mode
- KAMA - Kaufman Adaptive Moving Average
- LINEARREG - Linear Regression
- LINEARREG_ANGLE - Linear Regression Angle
- LINEARREG_INTERCEPT - Linear Regression Intercept
- LINEARREG_SLOPE - Linear Regression Slope
- MACD - Moving Average Convergence/Divergence [Unstable]
- MACDEXT - MACD with controllable MA type
- MAMA - MESA Adaptive Moving Average
- MEDPRICE - Median Price
- MFI - Money Flow Index [No Incremental]
- MIDPOINT - MidPoint over period
- MIDPRICE - Midpoint Price over period
- MINUS_DI - Minus Directional Indicator
- MINUS_DM - Minus Directional Movement
- MOM - Momentum
- NATR - Normalized Average True Range
- OBV - On Balance Volume
- PLUS_DI - Plus Directional Indicator
- PLUS_DM - Plus Directional Movement
- PPO - Percentage Price Oscillator
- RENKO - Renko Chart
- RMA - Rolling Moving Average [Untested]
- ROC - Rate of change : ((price/prevPrice)-1)*100
- ROCP - Rate of change Percentage: (price-prevPrice)/prevPrice
- ROCR - Rate of change ratio: (price/prevPrice)
- ROCR100 - Rate of change ratio 100 scale: (price/prevPrice)*100
- RSI - Relative Strength Index
- SAR - Parabolic SAR
- SAREXT - Parabolic SAR - Extended
- SMA - Simple Moving Average
- STOCH - Stochastic [No Incremental]
- STOCHF - Stochastic Fast
- STOCHRSI - Stochastic Relative Strength Index
- SUPERTREND - Super Trend Indicator
- T3 - Triple Exponential Moving Average (T3)
- TEMA - Triple Exponential Moving Average
- TPO - Time Price Opportunity
- TRANGE - True Range
- TRIMA - Triangular Moving Average
- TRIX - 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
- TSF - Time Series Forecast
- TYPPRICE - Typical Price
- ULTOSC - Ultimate Oscillator
- VEGAS - VEGAS Channel and Trend Boundary EMAs [Untested]
- VWAP - Volume Weighted Average Price
- WCLPRICE - Weighted Close Price
- WILLR - Williams' %R
- WMA - Weighted Moving Average
Statistical Analysis
- ALPHA - Alpha: Measures excess returns over market
- BETA - Beta: Measures sensitivity to market volatility
- CALMAR - Calmar Ratio: Annual return to maximum drawdown ratio
- CORREL - Pearson's Correlation Coefficient
- DRAWDOWN - Maximum Drawdown: Maximum potential loss
- KELLY - Kelly Criterion: Optimal position sizing
- MAX - Highest value over a specified period
- MIN - Lowest value over a specified period
- SHARPE - Sharpe Ratio: Risk-adjusted return measure
- SORTINO - Sortino Ratio: Downside risk-adjusted returns
- STDDEV - Standard Deviation
- SUM - Summation
- VAR - Variance
- WINRATE - Win Rate: Strategy success probability
Contributing
We are passionate about supporting contributors of all levels of experience and would love to see you get involved in the project. See the contributing guide to get started.
License
This project is licensed under either of the following licenses, at your option: - Apache License, Version 2.0, (LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0) - MIT license (LICENSE-MIT or https://opensource.org/licenses/MIT)
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in kand by you, as defined in the Apache-2.0 license, shall be dually licensed as above, without any additional terms or conditions.