Linear Regression Slope
period = 14 Overview
The Linear Regression Slope quantifies the exact rate of price change per bar by calculating the slope coefficient of the best fit line through recent data, providing a precise mathematical measurement of trend velocity that reveals acceleration and deceleration patterns before they become visually apparent. This slope value represents the average price change per time unit over the lookback period, with positive slopes confirming uptrends where each bar theoretically adds that amount to price, while negative slopes quantify the rate of decline in downtrends. When the slope increases from bar to bar, it signals trend acceleration as momentum builds, creating ideal entry conditions for trend followers who seek to capture the meat of strong directional moves. Conversely, decreasing slope values warn of trend deceleration even while prices continue rising, providing advance notice of potential reversals that simple price analysis misses. The indicator excels at identifying divergences where price makes new highs but slope decreases, revealing weakening momentum that often precedes significant tops, or where price makes new lows with rising slope indicating selling exhaustion. Systematic traders particularly value the slope for position sizing and risk management, as higher absolute slope values justify larger positions in trending markets while near zero slopes suggest reduced exposure during consolidations.
Implementation Examples
Get started with Linear Regression Slope in a few lines:
use vectorta::indicators::linearreg_slope::{linearreg_slope, LinearRegSlopeInput, LinearRegSlopeParams};
use vectorta::utilities::data_loader::{Candles, read_candles_from_csv};
// Using with a price slice
let prices = vec![100.0, 101.0, 102.2, 101.5, 103.0, 104.0];
let params = LinearRegSlopeParams { period: Some(14) }; // Default is 14
let input = LinearRegSlopeInput::from_slice(&prices, params);
let result = linearreg_slope(&input)?;
// Using with Candles (defaults: period=14, source="close")
let candles: Candles = read_candles_from_csv("data/sample.csv")?;
let input = LinearRegSlopeInput::with_default_candles(&candles);
let result = linearreg_slope(&input)?;
// Access the slope values
for value in result.values {
println!("slope: {}", value);
} API Reference
Input Methods ▼
// From price slice
LinearRegSlopeInput::from_slice(&[f64], LinearRegSlopeParams) -> LinearRegSlopeInput
// From candles with custom source
LinearRegSlopeInput::from_candles(&Candles, &str, LinearRegSlopeParams) -> LinearRegSlopeInput
// From candles with default params (close, period=14)
LinearRegSlopeInput::with_default_candles(&Candles) -> LinearRegSlopeInput Parameters Structure ▼
#[derive(Debug, Clone)]
pub struct LinearRegSlopeParams {
pub period: Option<usize>, // Default: 14
} Output Structure ▼
#[derive(Debug, Clone)]
pub struct LinearRegSlopeOutput {
pub values: Vec<f64>, // Slope values per input index (NaN during warmup)
} Validation, Warmup & NaNs ▼
period >= 2andperiod <= data.len(); otherwiseLinearRegSlopeError::InvalidPeriod.- All values
NaNtriggersLinearRegSlopeError::AllValuesNaN. - There must be at least
periodvalid points after the first finite value; otherwiseLinearRegSlopeError::NotEnoughValidData. - Warmup: indices before
first_valid + period - 1areNaN; output length equals input length. linearreg_slope_into_slicerequiresdst.len() == data.len(); otherwiseLinearRegSlopeError::InvalidOutputLength.- Batch API requires a batch kernel; wrong kernel yields
LinearRegSlopeError::KernelMismatch.
Error Handling ▼
use vectorta::indicators::linearreg_slope::{linearreg_slope, LinearRegSlopeError};
match linearreg_slope(&input) {
Ok(output) => process(output.values),
Err(LinearRegSlopeError::EmptyData) =>
eprintln!("Input data is empty"),
Err(LinearRegSlopeError::InvalidPeriod { period, data_len }) =>
eprintln!("Invalid period {} for data length {}", period, data_len),
Err(LinearRegSlopeError::NotEnoughValidData { needed, valid }) =>
eprintln!("Need {} valid points, only {}", needed, valid),
Err(LinearRegSlopeError::AllValuesNaN) =>
eprintln!("All values are NaN"),
Err(LinearRegSlopeError::KernelMismatch) =>
eprintln!("Batch API requires a batch kernel"),
Err(LinearRegSlopeError::InvalidOutputLength { output_len, expected_len }) =>
eprintln!("Output length {} != expected {}", output_len, expected_len),
} Python Bindings
Basic Usage ▼
Calculate Linear Regression Slope using NumPy arrays (default period = 14):
import numpy as np
from vectorta import linearreg_slope
# Prepare price data as NumPy array
prices = np.array([100.0, 101.0, 102.2, 101.5, 103.0, 104.0], dtype=np.float64)
# Calculate with defaults (period=14)
result = linearreg_slope(prices, period=14)
# Or specify kernel for performance ("auto", "scalar", "avx2", "avx512")
result = linearreg_slope(prices, period=14, kernel="auto")
print("slope:", result) Streaming Real-time Updates ▼
Process real-time updates; returns None during warmup:
from vectorta import LinearRegSlopeStream
stream = LinearRegSlopeStream(period=14)
for price in price_feed:
value = stream.update(price)
if value is not None:
print("slope:", value) Batch Parameter Optimization ▼
Test multiple period values efficiently:
import numpy as np
from vectorta import linearreg_slope_batch
prices = np.array([...], dtype=np.float64)
# (start, end, step)
results = linearreg_slope_batch(prices, period_range=(5, 20, 5), kernel="auto")
print(results["values"].shape) # (num_periods, len(prices))
print(results["periods"]) CUDA Acceleration ▼
CUDA support for Linear Regression Slope is currently under development. The API will follow the same pattern as other CUDA-enabled indicators.
# Coming soon: CUDA-accelerated Linear Regression Slope calculations
#
# from vectorta import linearreg_slope_cuda_batch, linearreg_slope_cuda_many_series_one_param
# import numpy as np
#
# # Option 1: One Series, Many Parameters (parameter optimization)
# results = linearreg_slope_cuda_batch(
# data=prices,
# period_range=(5, 20, 1),
# device_id=0
# )
# # Returns:
# # - results['values']: 2D array [num_combinations x len(prices)]
# # - results['periods']: array of period values tested
#
# # Option 2: Many Series, One Parameter Set (portfolio processing)
# data_tm = np.array([...]) # [time_steps, num_assets]
# results = linearreg_slope_cuda_many_series_one_param(
# data_tm=data_tm,
# period=14,
# device_id=0
# )
# # Also supports zero-copy variants with pre-allocated outputs. JavaScript/WASM Bindings
Basic Usage ▼
Calculate Linear Regression Slope in JavaScript/TypeScript:
import { linearreg_slope_js } from 'vectorta-wasm';
const prices = new Float64Array([100.0, 101.0, 102.2, 101.5, 103.0, 104.0]);
// Calculate slope with specified period
const values = linearreg_slope_js(prices, 14);
console.log('slope:', values); Memory-Efficient Operations ▼
Use zero-copy operations for large datasets:
import { linearreg_slope_alloc, linearreg_slope_free, linearreg_slope_into, memory } from 'vectorta-wasm';
const prices = new Float64Array([/* your data */]);
const n = prices.length;
// Allocate WASM memory
const inPtr = linearreg_slope_alloc(n);
const outPtr = linearreg_slope_alloc(n);
// Copy input data
new Float64Array(memory.buffer, inPtr, n).set(prices);
// Compute directly into allocated memory: (in_ptr, out_ptr, len, period)
linearreg_slope_into(inPtr, outPtr, n, 14);
// Read results (copy out)
const slope = new Float64Array(memory.buffer, outPtr, n).slice();
// Free memory
linearreg_slope_free(inPtr, n);
linearreg_slope_free(outPtr, n); Batch Processing ▼
Evaluate multiple periods via WASM batch APIs:
import { linearreg_slope_batch_js } from 'vectorta-wasm';
const prices = new Float64Array([/* historical prices */]);
// High-level batch API (returns object with values/combos/rows/cols)
const cfg = { period_range: [5, 20, 5] };
const out = linearreg_slope_batch_js(prices, cfg);
console.log(out.rows, out.cols, out.combos); Performance Analysis
Across sizes, Rust CPU runs about 1.02× slower than Tulip C in this benchmark.
AMD Ryzen 9 9950X (CPU) | NVIDIA RTX 4090 (GPU) | Benchmarks: 2026-01-05
CUDA note
In our benchmark workload, the Rust CPU implementation is faster than CUDA for this indicator. Prefer the Rust/CPU path unless your workload differs.