ta-rs

repository·master·Indexed 21 days ago

https://github.com/greyblake/ta-rs

A technical analysis library for Rust providing financial indicators including trend indicators (EMA, SMA), oscillators (RSI, MACD, Stochastic, PPO, CCI, MFI), and volatility tools (Bollinger Bands, Average True Range, Chandelier Exit, Keltner Channel). It utilizes Data Items and Indicators traits to process price and volume information.

Tokens
9.3K
Snippets
34
Records
43
Agent score
71%

What's inside ta

  1. How data items and indicators work

    master

    The library is built around two main concepts: Data Items and Indicators.

    Data Items

    A data item representing a stock quote can implement several traits to provide necessary price/volume information. While you can implement your own, it is recommended to use DataItem. Required traits for indicators:

    • Open
    • High
    • Low
    • Close
    • Volume

    Indicators

    Indicators process these data items and typically implement these traits:

    • Next<T> (commonly Next<f64> or Next<&DataItem>) - used to feed a new value into the indicator and retrieve the calculated result.
    • Reset - used to reset the indicator state.
    • Debug, Display, Default, Clone - standard Rust traits.
  2. How indicators work in ta-rs

    master

    In ta-rs, every technical indicator is implemented as a data structure that maintains its own internal state and parameters. Indicators are designed to be used sequentially as new data points arrive.

    To use an indicator, you typically follow this lifecycle:

    1. Initialize: Create a new instance of the indicator using its new() method (e.g., ExponentialMovingAverage::new(period)).
    2. Update: Feed new data into the indicator using the .next() method. This updates the internal state and returns the calculated value.
    3. Reset: If you need to clear the indicator's state to start fresh, use the .reset() method.

    Indicators are generic over the input type via the Next<T> trait, meaning they can accept simple f64 values or more complex DataItem structures.

    use ta::indicators::ExponentialMovingAverage;
    use ta::Next;
    
    // 1. Initialize
    let mut ema = ExponentialMovingAverage::new(3).unwrap();
    
    // 2. Update with new data points
    assert_eq!(ema.next(2.0), 2.0);
    assert_eq!(ema.next(5.0), 3.5);
  3. Core traits: Next and Reset

    master

    The ta-rs library is built around two core traits that define how indicators behave:

    • Next<T>: This is the primary interface for advancing an indicator. It takes a new value of type T (often f64 or DataItem), updates the indicator's internal state, and returns the resulting indicator value. Because it is generic, indicators can be used with different data types.
    • Reset: This trait provides a way to reset the indicator to its initial state, clearing any accumulated history or stateful calculations.
  4. Use an indicator with `ExponentialMovingAverage`

    master

    Indicators in ta are typically initialized with a period and then updated using the .next() method. Note that initialization can return an error if an invalid length (e.g., 0) is provided.

    use ta::indicators::ExponentialMovingAverage;
    use ta::Next;
    
    // it can return an error, when an invalid length is passed (e.g. 0)
    let mut ema = ExponentialMovingAverage::new(3).unwrap();
    
    assert_eq!(ema.next(2.0), 2.0);
    assert_eq!(ema.next(5.0), 3.5);
    assert_eq!(ema.next(1.0), 2.25);
    assert_eq!(ema.next(6.25), 4.25);
  5. List of available technical indicators

    master

    The ta library provides a variety of indicators categorized by type:

    Trend Indicators

    • Exponential Moving Average (EMA)
    • Simple Moving Average (SMA)

    Oscillators

    • Relative Strength Index (RSI)
    • Fast Stochastic
    • Slow Stochastic
    • Moving Average Convergence Divergence (MACD)
    • Percentage Price Oscillator (PPO)
    • Commodity Channel Index (CCI)
    • Money Flow Index (MFI)

    Other Indicators

    • Minimum, Maximum
    • True Range, Average True Range (AR)
    • Standard Deviation (SD), Mean Absolute Deviation (MAD)
    • Efficiency Ratio (ER)
    • Bollinger Bands (BB)
    • Chandelier Exit (CE)
    • Keltner Channel (KC)
    • Rate of Change (ROC)
    • On Balance Volume (OBV)
  6. Use the MoneyFlowIndex indicator

    master

    The MoneyFlowIndex (MFI) is a volume and price-based oscillator used to measure buying and selling pressure. It is often referred to as a volume-weighted RSI.

    To use it, initialize the indicator with a specific period using MoneyFlowIndex::new(period). You then feed data into it using the .next() method. The input must provide High, Low, Close, and Volume data (e.g., via a DataItem or a custom struct implementing those traits).

    use ta::indicators::MoneyFlowIndex;
    use ta::{Next, DataItem};
    
    // Initialize MFI with a period of 3
    let mut mfi = MoneyFlowIndex::new(3).unwrap();
    
    // Create a data item with price and volume information
    let di = DataItem::builder()
                 .high(3.0)
                 .low(1.0)
                 .close(2.0)
                 .open(1.5)
                 .volume(1000.0)
                 .build().unwrap();
    
    // Calculate the next MFI value
    mfi.next(&di);
  7. Use the Moving Average Convergence Divergence (MACD) indicator

    master

    The MovingAverageConvergenceDivergence indicator (also aliased as MACD) calculates three time series from price data (typically closing prices):

    1. MACD series: The difference between a fast Exponential Moving Average (EMA) and a slow EMA.
    2. Signal series: An EMA of the MACD series itself.
    3. Histogram (Divergence) series: The difference between the MACD series and the signal series.

    Initialization

    • Use MovingAverageConvergenceDivergence::new(fast_period, slow_period, signal_period) to specify custom periods. Returns a Result.
    • Use MovingAverageConvergenceDivergence::default() for standard periods (Fast: 12, Slow: 26, Signal: 9).

    Updating and Output

    Implement the Next trait to feed data into the indicator. You can pass a raw f64 or a type implementing the Close trait.

    Each call to .next() returns a MovingAverageConvergenceDivergenceOutput struct containing the macd, signal, and histogram values. This output can also be converted into a tuple (f64, f64, f64) via the From trait.

    use ta::indicators::MovingAverageConvergenceDivergence as Macd;
    use ta::Next;
    
    // Initialize with custom periods
    let mut macd = Macd::new(3, 6, 4).unwrap();
    
    // Feed a new price point and get the output
    let output = macd.next(3.0);
    
    println!("MACD: {}, Signal: {}, Histogram: {}", output.macd, output.signal, output.histogram);
    
    // Or convert to a tuple (macd, signal, histogram)
    let (m, s, h): (f64, f64, f64) = output.into();
  8. Use the Chandelier Exit indicator

    master

    The Chandelier Exit (CE) is a trailing stop-loss indicator based on the Average True Range (ATR). It helps traders stay in a trend by providing stop-loss levels: a long level for uptrends and a short level for downtrends.

    Formulas

    • Chandelier Exit (long) = Max(period) - ATR(period) * multiplier
    • Chandelier Exit (short) = Min(period) + ATR(period) * multiplier

    Implementation

    You can initialize the indicator using ChandelierExit::new(period, multiplier) or use the Default implementation which uses a period of 22 and a multiplier of 3.0. To process data, use the .next() method with a type that implements Low, High, and Close (such as a DataItem).

    use ta::indicators::ChandelierExit;
    use ta::{Next, DataItem};
    
    let value1 = DataItem::builder()
        .open(21.0).high(22.0).low(20.0).close(21.0).volume(1.0).build().unwrap();
    
    let mut ce = ChandelierExit::default();
    
    let first = ce.next(&value1);
    assert_eq!(first.long, 16.0);
    assert_eq!(first.short, 26.0);
  9. Calculate Average True Range (ATR)

    master

    The AverageTrueRange indicator measures market volatility. This implementation uses an Exponential Moving Average (EMA) of the True Range (TR) values.

    To use it, initialize the indicator with a specific smoothing period using AverageTrueRange::new(period) and then feed it price data using the .next() method. The .next() method accepts either a raw f64 (representing the true range) or a reference to a type that implements the High, Low, and Close traits (such as a bar or candle object).

    use ta::indicators::AverageTrueRange;
    use ta::DataItem;
    
    fn main() {
        // Initialize ATR with a period of 3
        let mut indicator = AverageTrueRange::new(3).unwrap();
    
        // Example data: (open, high, low, close, expected_atr)
        let data = vec![
            (9.7, 10.0, 9.0, 9.5, 1.0),
            (9.9, 10.4, 9.8, 10.2, 0.95),
            (10.1, 10.7, 9.4, 9.7, 1.125),
            (9.1, 9.2, 8.1, 8.4, 1.3625),
        ];
    
        for (open, high, low, close, atr) in data {
            let di = DataItem::builder()
                .high(high)
                .low(low)
                .close(close)
                .open(open)
                .volume(1000.0)
                .build().unwrap();
            
            // Pass the DataItem reference to .next()
            let result = indicator.next(&di);
            println!("ATR: {}", result);
        }
    }