PairedStatistics

Struct PairedStatistics 

Source
pub struct PairedStatistics<T> { /* private fields */ }
Expand description

A structure that computes various statistics over a fixed-size window of paired values.

PairedStatistics<T> maintains a circular buffer of paired values and computes statistical measures such as covariance, correlation, beta, etc.

The structure automatically updates statistics as new values are added and old values are removed from the window, making it efficient for rolling statistics analysis.

Implementations§

Source§

impl<T> PairedStatistics<T>
where T: Default + Clone + Float,

Source

pub fn new(period: usize) -> Self

Creates a new PairedStatistics instance with the specified period.

§Arguments
  • period - The period of the statistics
§Returns
  • Self - The PairedStatistics instance
Source

pub fn period(&self) -> usize

Returns the period of the statistics

§Returns
  • usize - The period of the statistics
Source

pub fn reset(&mut self) -> &mut Self

Resets the statistics

§Returns
  • &mut Self - The statistics object
Source

pub fn recompute(&mut self) -> &mut Self

Recomputes the paired statistics, could be called to avoid prolonged compounding of floating rounding errors

§Returns
  • &mut Self - The rolling moments object
Source

pub fn next(&mut self, (x, y): (T, T)) -> &mut Self

Updates the paired statistical calculations with a new value pair in the time series

Incorporates a new data point pair into the rolling window, maintaining the specified window size by removing the oldest pair when necessary. This core method provides the foundation for all paired statistical measures that examine relationships between two variables.

§Arguments
  • value - A tuple containing the paired values (x, y) to incorporate into calculations
§Returns
  • &mut Self - The updated statistics object for method chaining
Source

pub const fn ddof(&self) -> bool

Returns the Delta Degrees of Freedom

§Returns
  • bool - The Delta Degrees of Freedom
Source

pub const fn set_ddof(&mut self, ddof: bool) -> &mut Self

Sets the Delta Degrees of Freedom

§Arguments
  • ddof - The Delta Degrees of Freedom
§Returns
  • &mut Self - The statistics object
Source

pub fn cov(&self) -> Option<T>

Returns the covariance of the paired values in the rolling window

Covariance measures how two variables change together, indicating the direction of their linear relationship. This fundamental measure of association provides:

  • Directional relationship analysis between paired time series
  • Foundation for correlation, beta, and regression calculations
  • Raw measurement of how variables move in tandem
  • Basis for portfolio diversification and risk assessments
§Returns
  • Option<T> - The covariance of the values in the window, or None if the window is not full
§Examples
use ta_statistics::PairedStatistics;
use assert_approx_eq::assert_approx_eq;

let mut stats = PairedStatistics::new(3);
let mut results = vec![];
let inputs = [(2.0, 1.0), (4.0, 3.0), (6.0, 2.0), (8.0, 5.0), (10.0, 7.0)];
inputs.iter().for_each(|i| {
    stats.next(*i).cov().map(|v| results.push(v));
});

let expected: [f64; 3] = [0.6667, 1.3333, 3.3333];
 for (i, e) in expected.iter().enumerate() {
 assert_approx_eq!(e, results[i], 0.001);
 }

stats.reset().set_ddof(true);
results = vec![];
inputs.iter().for_each(|i| {
    stats.next(*i).cov().map(|v| results.push(v));
});

let expected: [f64; 3] = [1.0, 2.0, 5.0];
for (i, e) in expected.iter().enumerate() {
   assert_approx_eq!(e, results[i], 0.0001);
}
Source

pub fn corr(&self) -> Option<T>

Returns the correlation coefficient (Pearson’s r) of paired values in the rolling window

Correlation normalizes covariance by the product of standard deviations, producing a standardized measure of linear relationship strength between -1 and 1:

  • Quantifies the strength and direction of relationships between variables
  • Enables cross-pair comparison on a standardized scale
  • Provides the foundation for statistical arbitrage models
  • Identifies regime changes in intermarket relationships
§Returns
  • Option<T> - The correlation coefficient in the window, or None if the window is not full
§Examples
use ta_statistics::PairedStatistics;
use assert_approx_eq::assert_approx_eq;

let mut stats = PairedStatistics::new(3);
let mut results = vec![];
let inputs = [
    (0.496714, 0.115991),
    (-0.138264, -0.329650),
    (0.647689, 0.574363),
    (1.523030, 0.109481),
    (-0.234153, -1.026366),
    (-0.234137, -0.445040),
    (1.579213, 0.599033),
    (0.767435, 0.694328),
    (-0.469474, -0.782644),
    (0.542560, -0.326360)
];

inputs.iter().for_each(|i| {
    stats.next(*i).corr().map(|v| results.push(v));
});
let expected: [f64; 8] = [0.939464, 0.458316, 0.691218, 0.859137, 0.935658, 0.858379, 0.895148, 0.842302,];
for (i, e) in expected.iter().enumerate() {
    assert_approx_eq!(e, results[i], 0.0001);
}
Source

pub fn beta(&self) -> Option<T>

Returns the beta coefficient of the paired values in the rolling window

Beta measures the relative volatility between two time series, indicating the sensitivity of one variable to changes in another:

  • Quantifies systematic risk exposure between related instruments
  • Determines optimal hedge ratios for risk management
  • Provides relative sensitivity analysis for pair relationships
  • Serves as a key input for factor modeling and attribution analysis
§Returns
  • Option<T> - The beta coefficient in the window, or None if the window is not full
§Examples
use ta_statistics::PairedStatistics;
use assert_approx_eq::assert_approx_eq;

let mut stats = PairedStatistics::new(3);
let mut results = vec![];
let inputs = [
     (0.015, 0.010),
     (0.025, 0.015),
     (-0.010, -0.005),
     (0.030, 0.020),
     (0.005, 0.010),
     (-0.015, -0.010),
     (0.020, 0.015),
];

inputs.iter().for_each(|i| {
    stats.next(*i).beta().map(|v| results.push(v));
});

let expected: [f64; 5] = [1.731, 1.643, 1.553, 1.429, 1.286];
for (i, e) in expected.iter().enumerate() {
    assert_approx_eq!(e, results[i], 0.001);
}

Trait Implementations§

Source§

impl<T: Clone> Clone for PairedStatistics<T>

Source§

fn clone(&self) -> PairedStatistics<T>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug> Debug for PairedStatistics<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T> Freeze for PairedStatistics<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for PairedStatistics<T>
where T: RefUnwindSafe,

§

impl<T> Send for PairedStatistics<T>
where T: Send,

§

impl<T> Sync for PairedStatistics<T>
where T: Sync,

§

impl<T> Unpin for PairedStatistics<T>
where T: Unpin,

§

impl<T> UnwindSafe for PairedStatistics<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.