Import polars_talib
masterTo use the extension, import polars and polars_talib (commonly aliased as plta).
import polars
import polars_talib as pltarepository·master·Indexed 42 days ago
https://github.com/yvictor/polars_ta_extensionA 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.
To use the extension, import polars and polars_talib (commonly aliased as plta).
import polars
import polars_talib as pltaTo use the safe Rust wrapper for Ta-Lib in your project, add the talib crate using cargo.
cargo add talibTo 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:
ta_initialize() at the start of your application.TimePeriodKwargs or TimePeriodKwargsBuilder to specify parameters like timeperiod.Vec<f64>), the length of the data, and the configuration object to the indicator function (e.g., ta_rsi).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();
}Install the extension using pip:
pip install polars_talibCertain momentum indicators return multiple values encapsulated in a Polars Struct. You can access the individual components by name.
Returns a struct with fields:
aroondown: Float64aroonup: Float64Returns a struct with fields:
macd: Float64macdsignal: Float64macdhist: Float64macdext and macdfix variants also return this same structure.stoch)Returns a struct with fields:
slowk: Float64slowd: Float64stochf)Returns a struct with fields:
fastk: Float64fastd: Float64stochrsi)Returns a struct with fields:
fastk: Float64fastd: Float64The 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.
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()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"),
)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"),
)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
),
)To see which functions belong to which indicator groups (e.g., Momentum, Volatility, Pattern Recognition), use plta.get_function_groups().
import polars_talib as plta
# dict of functions by group
plta.get_function_groups()You can retrieve a list of all available technical analysis functions using plta.get_functions().
import polars_talib as plta
# list of functions
plta.get_functions()