pub struct Matrix { /* private fields */ }Expand description
A contiguous row-major dense matrix.
Implementations§
Source§impl Matrix
impl Matrix
Sourcepub fn new(
rows: usize,
cols: usize,
data: Vec<f64>,
) -> Result<Matrix, MatrixError>
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
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}Sourcepub fn as_mut_slice(&mut self) -> &mut [f64]
pub fn as_mut_slice(&mut self) -> &mut [f64]
Mutable row-major backing storage.
Trait Implementations§
impl StructuralPartialEq for Matrix
Auto Trait Implementations§
impl Freeze for Matrix
impl RefUnwindSafe for Matrix
impl Send for Matrix
impl Sync for Matrix
impl Unpin for Matrix
impl UnsafeUnpin for Matrix
impl UnwindSafe for Matrix
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more