Skip to main content

ferric_alpha/performance/
pyfolio.rs

1use std::collections::{BTreeMap, BTreeSet};
2
3use polars::prelude::{DataFrame, DataType, NamedFrom, Series, SortMultipleOptions};
4
5use crate::data::required_column;
6use crate::error::{FerricAlphaError, Result};
7use crate::performance::frame::date_column;
8use crate::performance::portfolio::filter_factor_data;
9use crate::performance::{PortfolioOptions, WeightOptions};
10use crate::{Period, factor_cumulative_returns, factor_positions, factor_returns};
11
12#[derive(Debug, Clone)]
13pub struct PyfolioInput {
14    pub returns: DataFrame,
15    pub positions: DataFrame,
16    pub benchmark: Option<DataFrame>,
17}
18
19pub fn create_pyfolio_input(
20    factor_data: &DataFrame,
21    period: Period,
22    capital: Option<f64>,
23    options: PortfolioOptions,
24    benchmark_period: Option<Period>,
25    sessions: Option<&DataFrame>,
26) -> Result<PyfolioInput> {
27    if capital.is_some_and(|capital| !capital.is_finite() || capital <= 0.0) {
28        return Err(FerricAlphaError::InvalidOption {
29            option: "capital",
30            reason: "capital must be finite and positive",
31        });
32    }
33
34    let wealth = if period.count() == 1 {
35        factor_cumulative_returns(factor_data, period, options.clone())?
36    } else {
37        overlapping_daily_wealth(factor_data, period, options.clone(), sessions)?
38    };
39    let returns = changes_from_wealth(&wealth, "return")?;
40    let mut positions = factor_positions(factor_data, period, options, sessions)?;
41    if let Some(capital) = capital {
42        positions = scale_positions(&positions, &wealth, capital)?;
43    }
44
45    let benchmark = benchmark_period
46        .filter(|period| {
47            factor_data
48                .column(&format!("forward_return_{}", period.label()))
49                .is_ok()
50        })
51        .map(|period| {
52            let benchmark_options = PortfolioOptions::default().with_weight_options(
53                WeightOptions::default()
54                    .with_demeaned(false)
55                    .with_group_adjust(false)
56                    .with_equal_weight(true),
57            );
58            let benchmark_wealth =
59                factor_cumulative_returns(factor_data, period, benchmark_options)?;
60            changes_from_wealth(&benchmark_wealth, "benchmark")
61        })
62        .transpose()?;
63
64    Ok(PyfolioInput {
65        returns,
66        positions,
67        benchmark,
68    })
69}
70
71#[derive(Debug)]
72struct ActiveReturnSleeve {
73    expiry_index: usize,
74    daily_return: f64,
75}
76
77fn overlapping_daily_wealth(
78    factor_data: &DataFrame,
79    period: Period,
80    options: PortfolioOptions,
81    sessions: Option<&DataFrame>,
82) -> Result<DataFrame> {
83    let filtered = filter_factor_data(factor_data, &options)?;
84    let returns = factor_returns(
85        &filtered,
86        crate::performance::ReturnOptions::default().with_weight_options(options.weight_options),
87    )?;
88    let period_label = period.label();
89    let dates = returns
90        .column("date")?
91        .as_materialized_series()
92        .datetime()?;
93    let periods = returns.column("period")?.as_materialized_series().str()?;
94    let values = returns
95        .column("factor_return")?
96        .as_materialized_series()
97        .f64()?;
98    let date_dtype = returns.column("date")?.dtype().clone();
99    let mut returns_by_date = BTreeMap::new();
100    for index in 0..returns.height() {
101        if periods.get(index) != Some(period_label.as_str()) {
102            continue;
103        }
104        let date = dates
105            .physical()
106            .get(index)
107            .ok_or(FerricAlphaError::NullKey)?;
108        if returns_by_date
109            .insert(date, values.get(index).filter(|value| value.is_finite()))
110            .is_some()
111        {
112            return Err(FerricAlphaError::DuplicateKey);
113        }
114    }
115    let session_values = pyfolio_sessions(sessions, &date_dtype, returns_by_date.keys().copied())?;
116    let mut active = Vec::<ActiveReturnSleeve>::new();
117    let mut output_dates = Vec::with_capacity(session_values.len());
118    let mut output_wealth = Vec::with_capacity(session_values.len());
119    let mut wealth = 1.0;
120
121    for (session_index, session_date) in session_values.iter().enumerate() {
122        active.retain(|sleeve| sleeve.expiry_index > session_index);
123        if let Some(Some(forward_return)) = returns_by_date.get(session_date).copied() {
124            let base = 1.0 + forward_return;
125            if !base.is_finite() || base < 0.0 {
126                return Err(FerricAlphaError::InvalidInput {
127                    operation: "create_pyfolio_input",
128                    reason: "forward return cannot be converted to daily sleeve return",
129                });
130            }
131            active.push(ActiveReturnSleeve {
132                expiry_index: session_index.saturating_add(period.count() as usize),
133                daily_return: base.powf(1.0 / period.count() as f64) - 1.0,
134            });
135        }
136
137        output_dates.push(*session_date);
138        output_wealth.push(wealth);
139        if !active.is_empty() {
140            let daily_return =
141                active.iter().map(|sleeve| sleeve.daily_return).sum::<f64>() / active.len() as f64;
142            wealth *= 1.0 + daily_return;
143            if !wealth.is_finite() {
144                return Err(FerricAlphaError::InvalidInput {
145                    operation: "create_pyfolio_input",
146                    reason: "portfolio wealth must remain finite",
147                });
148            }
149        }
150    }
151
152    let frame = DataFrame::new(
153        output_dates.len(),
154        vec![
155            date_column("date", output_dates, &date_dtype)?,
156            Series::new("cumulative_return".into(), output_wealth).into(),
157        ],
158    )?;
159    Ok(frame.sort(["date"], SortMultipleOptions::default())?)
160}
161
162fn pyfolio_sessions(
163    sessions: Option<&DataFrame>,
164    date_dtype: &DataType,
165    inferred: impl Iterator<Item = i64>,
166) -> Result<Vec<i64>> {
167    let Some(sessions) = sessions else {
168        return Ok(inferred.collect::<BTreeSet<_>>().into_iter().collect());
169    };
170    if sessions.width() != 1 {
171        return Err(FerricAlphaError::InvalidInput {
172            operation: "create_pyfolio_input",
173            reason: "sessions must contain exactly one date column",
174        });
175    }
176    let date = required_column(sessions, "date")?;
177    if !matches!(date.dtype(), DataType::Datetime(_, _)) {
178        return Err(FerricAlphaError::InvalidDtype {
179            column: "date",
180            expected: "Datetime",
181            actual: date.dtype().to_string(),
182        });
183    }
184    if date.dtype() != date_dtype {
185        return Err(FerricAlphaError::TimezoneMismatch);
186    }
187    if date.null_count() > 0 {
188        return Err(FerricAlphaError::NullKey);
189    }
190    let values = date
191        .as_materialized_series()
192        .datetime()?
193        .physical()
194        .iter()
195        .map(|value| value.expect("validated session date"))
196        .collect::<BTreeSet<_>>();
197    Ok(values.into_iter().collect())
198}
199
200fn changes_from_wealth(wealth: &DataFrame, name: &str) -> Result<DataFrame> {
201    let values = wealth
202        .column("cumulative_return")?
203        .as_materialized_series()
204        .f64()?;
205    let mut returns = Vec::with_capacity(wealth.height());
206    let mut previous: Option<f64> = None;
207    for value in values.iter() {
208        let value = value.ok_or(FerricAlphaError::InvalidInput {
209            operation: "create_pyfolio_input",
210            reason: "cumulative wealth must not contain null values",
211        })?;
212        let change = match previous {
213            None => 0.0,
214            Some(previous) if previous != 0.0 => value / previous - 1.0,
215            Some(_) => {
216                return Err(FerricAlphaError::InvalidInput {
217                    operation: "create_pyfolio_input",
218                    reason: "cannot compute return after zero wealth",
219                });
220            }
221        };
222        if !change.is_finite() {
223            return Err(FerricAlphaError::InvalidInput {
224                operation: "create_pyfolio_input",
225                reason: "portfolio returns must remain finite",
226            });
227        }
228        returns.push(change);
229        previous = Some(value);
230    }
231    Ok(DataFrame::new(
232        wealth.height(),
233        vec![
234            wealth.column("date")?.clone(),
235            Series::new(name.into(), returns).into(),
236        ],
237    )?)
238}
239
240fn scale_positions(positions: &DataFrame, wealth: &DataFrame, capital: f64) -> Result<DataFrame> {
241    let wealth_dates = wealth.column("date")?.as_materialized_series().datetime()?;
242    let wealth_values = wealth
243        .column("cumulative_return")?
244        .as_materialized_series()
245        .f64()?;
246    let wealth_by_date = wealth_dates
247        .physical()
248        .iter()
249        .zip(wealth_values.iter())
250        .map(|(date, value)| {
251            Ok((
252                date.ok_or(FerricAlphaError::NullKey)?,
253                value.ok_or(FerricAlphaError::InvalidInput {
254                    operation: "create_pyfolio_input",
255                    reason: "cumulative wealth must not contain null values",
256                })?,
257            ))
258        })
259        .collect::<Result<BTreeMap<_, _>>>()?;
260    let position_dates = positions
261        .column("date")?
262        .as_materialized_series()
263        .datetime()?;
264    let position_values = positions
265        .column("position")?
266        .as_materialized_series()
267        .f64()?;
268    let scaled = position_dates
269        .physical()
270        .iter()
271        .zip(position_values.iter())
272        .map(|(date, position)| {
273            let date = date.ok_or(FerricAlphaError::NullKey)?;
274            let wealth = wealth_by_date
275                .range(..=date)
276                .next_back()
277                .map(|(_, wealth)| *wealth)
278                .unwrap_or(1.0);
279            let scaled = position.ok_or(FerricAlphaError::InvalidInput {
280                operation: "create_pyfolio_input",
281                reason: "positions must not contain null values",
282            })? * wealth
283                * capital;
284            if scaled.is_finite() {
285                Ok(scaled)
286            } else {
287                Err(FerricAlphaError::InvalidInput {
288                    operation: "create_pyfolio_input",
289                    reason: "capital positions must remain finite",
290                })
291            }
292        })
293        .collect::<Result<Vec<_>>>()?;
294
295    Ok(DataFrame::new(
296        positions.height(),
297        vec![
298            positions.column("date")?.clone(),
299            positions.column("asset")?.clone(),
300            Series::new("position".into(), scaled).into(),
301        ],
302    )?)
303}