Skip to main content

PortfolioSequence

Struct PortfolioSequence 

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

A rolling solve sequence over a fixed portfolio structure.

Built by PortfolioProblem::sequence or PortfolioProblem::sequence_with. Owns a Workspace, so equilibration and SMW-reduced factorizations persist across dates, and manages warm starts internally: each solve starts from the previous solution’s full primal/dual iterate.

Solution::solve_time on sequence solves covers iteration only; the one-time setup was paid when the sequence was constructed.

Implementations§

Source§

impl PortfolioSequence

Source

pub fn dimension(&self) -> usize

Number of portfolio weights.

Source

pub const fn settings(&self) -> &SolverSettings

Settings every solve in this sequence iterates with.

Source

pub const fn factorizations(&self) -> usize

Number of reduced factorizations built since construction (including the initial one). A stable count across rolling dates demonstrates factorization reuse.

Examples found in repository?
examples/sequence.rs (line 42)
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 solve_next( &mut self, step: &RebalanceStep, ) -> Result<Solution, PortfolioError>

Applies one step’s data changes, then solves, warm-started from the previous solution.

The step is validated in full before any state changes, so an Err leaves the sequence exactly as it was. The first solve of a sequence is cold; every later solve chains the previous full primal/dual iterate (unless the previous solve failed numerically, which would make a non-finite start).

§Errors

Returns PortfolioError when the step data has wrong dimensions or non-finite values, updates a constraint the base problem does not have (budget / turnover anchor), or moves the budget outside what the box constraints can reach.

Examples found in repository?
examples/sequence.rs (line 48)
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}

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> 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, 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.