Skip to main content

Matrix

Struct Matrix 

Source
pub struct Matrix { /* private fields */ }
Expand description

A contiguous row-major dense matrix.

Implementations§

Source§

impl Matrix

Source

pub fn new( rows: usize, cols: usize, data: Vec<f64>, ) -> Result<Matrix, MatrixError>

Builds a matrix from row-major data.

§Errors

Returns MatrixError::DimensionsOverflow if the dimensions overflow, or MatrixError::InvalidShape when the data length is wrong.

Examples found in repository?
examples/rebalance.rs (lines 8-14)
7fn portfolio(expected_returns: Vec<f64>) -> Result<PortfolioProblem, Box<dyn Error>> {
8    let factors = Matrix::new(
9        6,
10        2,
11        vec![
12            0.8, 0.1, 0.7, -0.2, 0.2, 0.9, -0.1, 0.8, -0.5, 0.3, -0.6, -0.4,
13        ],
14    )?;
15    Ok(PortfolioProblem::new(
16        factors,
17        FactorCovariance::Diagonal(vec![0.08, 0.05]),
18        vec![0.12, 0.10, 0.09, 0.11, 0.08, 0.10],
19        expected_returns,
20    )?
21    .with_risk_aversion(6.0)?
22    .with_bounds(vec![0.0; 6], vec![0.35; 6])?)
23}
More examples
Hide additional examples
examples/batch.rs (line 65)
59fn build_accounts(config: &Config) -> Result<Vec<BatchAccount>, Box<dyn Error>> {
60    // One shared model: exposures, factor covariance, and specific variance
61    // are identical across accounts.
62    let exposures: Vec<f64> = (0..config.assets * config.factors)
63        .map(|index| 0.3 * ((index + 1) as f64 * 12.9898).sin())
64        .collect();
65    let factors = Matrix::new(config.assets, config.factors, exposures)?;
66    let omega = FactorCovariance::Diagonal(
67        (0..config.factors)
68            .map(|index| 0.05 + 0.01 * index as f64)
69            .collect(),
70    );
71    let specific: Vec<f64> = (0..config.assets)
72        .map(|index| 0.08 + 0.04 * ((index * 7 % 13) as f64) / 13.0)
73        .collect();
74    let max_weight = (10.0 / config.assets as f64).min(1.0);
75    let uniform = vec![1.0 / config.assets as f64; config.assets];
76
77    (0..config.accounts)
78        .map(|account| {
79            let problem = PortfolioProblem::new(
80                factors.clone(),
81                omega.clone(),
82                specific.clone(),
83                expected_returns(config, account, 0),
84            )?
85            .with_risk_aversion(6.0)?
86            .with_bounds(vec![0.0; config.assets], vec![max_weight; config.assets])?
87            .with_quadratic_turnover(uniform.clone(), 0.5)?
88            .with_l1_turnover(uniform.clone(), vec![0.001; config.assets])?;
89            let steps = (0..config.dates)
90                .map(|date| RebalanceStep {
91                    expected_returns: (date > 0).then(|| expected_returns(config, account, date)),
92                    ..RebalanceStep::default()
93                })
94                .collect();
95            Ok(BatchAccount {
96                problem,
97                steps,
98                chain_previous_weights: true,
99            })
100        })
101        .collect()
102}
examples/sequence.rs (line 27)
22fn main() -> Result<(), Box<dyn Error>> {
23    let exposures: Vec<f64> = (0..ASSETS * FACTORS)
24        .map(|index| 0.3 * (index as f64 * 12.9898).sin())
25        .collect();
26    let problem = PortfolioProblem::new(
27        Matrix::new(ASSETS, FACTORS, exposures)?,
28        FactorCovariance::Diagonal(vec![0.06; FACTORS]),
29        vec![0.1; ASSETS],
30        expected_returns(0),
31    )?
32    .with_risk_aversion(6.0)?
33    .with_bounds(vec![0.0; ASSETS], vec![0.2; ASSETS])?
34    .with_quadratic_turnover(vec![1.0 / ASSETS as f64; ASSETS], 0.5)?;
35
36    let mut sequence = problem.sequence()?;
37    let mut previous_weights: Option<Vec<f64>> = None;
38
39    println!("date | status | iterations | new factorizations | one-way turnover");
40    println!("---|---|---|---|---");
41    for date in 0..DATES {
42        let factorizations_before = sequence.factorizations();
43        let step = RebalanceStep {
44            expected_returns: (date > 0).then(|| expected_returns(date)),
45            previous_weights: previous_weights.clone(),
46            ..RebalanceStep::default()
47        };
48        let solution = sequence.solve_next(&step)?;
49        if solution.status != SolveStatus::Solved {
50            return Err(format!(
51                "date {date} stopped with status '{}' after {} iterations",
52                solution.status, solution.iterations
53            )
54            .into());
55        }
56
57        let turnover = previous_weights.as_ref().map_or(0.0, |previous| {
58            solution
59                .x
60                .iter()
61                .zip(previous)
62                .map(|(new, old)| (new - old).abs())
63                .sum::<f64>()
64                / 2.0
65        });
66        println!(
67            "{date} | {} | {} | {} | {turnover:.6}",
68            solution.status,
69            solution.iterations,
70            sequence.factorizations() - factorizations_before,
71        );
72        previous_weights = Some(solution.x);
73    }
74    println!(
75        "total reduced factorizations across {DATES} dates: {}",
76        sequence.factorizations()
77    );
78    Ok(())
79}
Source

pub fn from_rows(rows: Vec<Vec<f64>>) -> Result<Matrix, MatrixError>

Builds a matrix from nested rows.

§Errors

Returns MatrixError::RaggedRows if row lengths differ.

Source

pub fn zeros(rows: usize, cols: usize) -> Matrix

Returns a zero-filled matrix.

Source

pub const fn rows(&self) -> usize

Number of rows.

Source

pub const fn cols(&self) -> usize

Number of columns.

Source

pub fn as_slice(&self) -> &[f64]

Row-major backing storage.

Source

pub fn as_mut_slice(&mut self) -> &mut [f64]

Mutable row-major backing storage.

Source

pub fn row(&self, row: usize) -> &[f64]

Returns one row.

Trait Implementations§

Source§

impl Clone for Matrix

Source§

fn clone(&self) -> Matrix

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for Matrix

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Index<(usize, usize)> for Matrix

Source§

type Output = f64

The returned type after indexing.
Source§

fn index(&self, _: (usize, usize)) -> &<Matrix as Index<(usize, usize)>>::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl IndexMut<(usize, usize)> for Matrix

Source§

fn index_mut( &mut self, _: (usize, usize), ) -> &mut <Matrix as Index<(usize, usize)>>::Output

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl PartialEq for Matrix

Source§

fn eq(&self, other: &Matrix) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Matrix

Auto Trait Implementations§

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.