polars_talib

repository·master·Indexed 42 days ago

https://github.com/yvictor/polars_ta_extension

A high-performance Polars extension for the TA-Lib technical analysis library, providing fast, vectorized technical indicator calculations within Polars DataFrames. Version 0.1.6 supports a wide range of indicators across Overlap Studies, Momentum, Volume, Cycle, Price Transform, Volatility, Pattern Recognition, and Statistic functions. It integrates directly into Polars expressions via a .ta namespace or standalone API calls, and supports grouped calculations using the .over() syntax.

Tokens
16.1K
Snippets
72
Records
94
Agent score
53%

What's inside polars_talib

  1. Use talib in Rust

    master

    To use talib, you must follow a lifecycle of initializing the library, performing calculations using specific indicator functions, and then shutting down the library.

    Key steps:

    1. Initialize: Call ta_initialize() at the start of your application.
    2. Configure: Use TimePeriodKwargs or TimePeriodKwargsBuilder to specify parameters like timeperiod.
    3. Calculate: Pass a pointer to your data (e.g., Vec<f64>), the length of the data, and the configuration object to the indicator function (e.g., ta_rsi).
    4. Shutdown: Call ta_shutdown() when the application is finished with Ta-Lib.
    use talib::common::{TimePeriodKwargs, ta_initialize, ta_shutdown};
    use talib::momentum::ta_rsi;
    
    fn main() {
        // Initialize Ta-Lib
        let _ = ta_initialize();
    
        // Sample close prices
        let close_prices: Vec<f64> = vec![1.087010, 1.087120, 1.087080, 1.087170, 1.087110, 1.087010, 1.087100, 1.087120, 1.087110, 1.087080, 1.087000, 1.086630, 1.086630, 1.086610, 1.086630, 1.086640, 1.086650, 1.086650, 1.086670, 1.086630];
    
        // Specify the RSI calculation parameters using a builder
        let kwargs = TimePeriodKwargsBuilder::default()
            .timeperiod(5)
            .build()
            .unwrap();
    
        // Calculate RSI using a pointer to the data
        let res = ta_rsi(close_prices.as_ptr(), close_prices.len(), &kwargs);
    
        // Process the result
        match res {
            Ok(rsi_values) => {
                for (index, value) in rsi_values.iter().enumerate() {
                    println!("RSI at index {}: {}", index, value);
                }
            }
            Err(e) => {
                println!("Error: {:?}", e);
            }
        }
    
        // Shutdown Ta-Lib
        let _ = ta_shutdown();
    }
  2. Momentum indicators returning a Struct

    master

    Certain momentum indicators return multiple values encapsulated in a Polars Struct. You can access the individual components by name.

    Aroon

    Returns a struct with fields:

    • aroondown: Float64
    • aroonup: Float64

    MACD (Moving Average Convergence Divergence)

    Returns a struct with fields:

    • macd: Float64
    • macdsignal: Float64
    • macdhist: Float64
    • Note: macdext and macdfix variants also return this same structure.

    Stochastic (stoch)

    Returns a struct with fields:

    • slowk: Float64
    • slowd: Float64

    Stochastic Fast (stochf)

    Returns a struct with fields:

    • fastk: Float64
    • fastd: Float64

    Stochastic RSI (stochrsi)

    Returns a struct with fields:

    • fastk: Float64
    • fastd: Float64
  3. Use Momentum indicators in Polars

    master

    The polars_ta_extension provides several momentum indicators as Polars expressions. These indicators can be used within Polars lazy or eager API calls to compute technical analysis metrics on financial time series data.

    Most momentum indicators require a single input series (e.g., close), while others require multiple series (e.g., high, low, close, volume). Some indicators return a single Float64 series, while others return a Struct containing multiple components.

  4. Use polars_talib for technical analysis with Polars

    master

    The polars_talib extension allows you to perform TA-Lib technical analysis directly within Polars expressions. A key pattern for handling multiple symbols (e.g., stock tickers) in a single DataFrame is to use the .over("Symbol") syntax. This ensures that indicators like SMA or MACD are calculated independently for each group.

    To use default column names (like open, high, low, close) without explicit mapping, it is recommended to lowercase your float columns using Polars selectors.

    import polars as pl
    import polars_talib as plta
    
    # Prepare data by lowercasing float columns to match TA-Lib defaults
    p = pl.scan_parquet("data.parquet").select(
        pl.col("Date"), 
        pl.col("Ticker").alias("Symbol"),
        pl.selectors.float().name.to_lowercase()
    )
    
    # Apply indicators using the .over() syntax for grouped calculations
    df = p.with_columns(
        plta.sma(timeperiod=5).over("Symbol").alias("sma5"),
        plta.macd(fastperiod=10, slowperiod=20, signalperiod=5).over("Symbol").alias("macd"),
    ).collect()
  5. Use technical indicators with Polars expressions

    master

    You can use technical indicators directly within Polars expressions using the .ta namespace on a column. This allows for seamless integration into with_columns calls.

    Note that some indicators like macd return a struct containing multiple fields (e.g., macd, macdsignal, macdhist), which can be accessed using .struct.field().

    df.with_columns(
        pl.col("close").ta.ema(5).alias("ema5"),
        pl.col("close").ta.macd(12, 26, 9).struct.field("macd"),
        pl.col("close").ta.macd(12, 26, 9).struct.field("macdsignal"),
        pl.col("open").ta.cdl2crows(pl.col("high"), pl.col("low"), pl.col("close")).alias("cdl2crows"),
        pl.col("close").ta.wclprice("high", "low").alias("wclprice"),
    )
  6. Calculate indicators for multiple symbols using .over()

    master

    When working with datasets containing multiple symbols (e.g., a 'symbol' or 'Ticker' column), use the Polars .over() syntax to ensure indicators are calculated independently for each group.

    df.with_columns(
        pl.col("close").ta.ema(5).over("symbol").alias("ema5"),
        pl.col("close").ta.macd(12, 26, 9).over("symbol").struct.field("macd"),
        pl.col("close").ta.macd(12, 26, 9).over("symbol").struct.field("macdsignal"),
        pl.col("open").ta.cdl2crows(
            pl.col("high"), pl.col("low"), pl.col("close")
        ).over("symbol").alias("cdl2crows"),
        pl.col("close").ta.wclprice("high", "low").over("symbol").alias("wclprice"),
    )
  7. Use polars_talib functions as standalone API calls

    master

    In addition to the .ta namespace, you can use polars_talib (as plta) functions directly. This provides a flexible interface similar to talib.abstract. You can pass specific columns or allow the function to use default columns if supported.

    df.with_columns(
        plta.ht_dcperiod(),
        plta.ht_dcperiod(pl.col("close")),
        plta.aroon(),
        plta.aroon(pl.col("high"), pl.col("low"), timeperiod=10),
        plta.wclprice(),
        plta.wclprice(
            pl.col("high"), pl.col("low"), pl.col("close"), 
            timeperiod=10
        ),
    )