Coverage for cvx/simulator/utils/grid.py: 100%
16 statements
« prev ^ index » next coverage.py v7.6.8, created at 2025-01-10 14:11 +0000
« prev ^ index » next coverage.py v7.6.8, created at 2025-01-10 14:11 +0000
1# Copyright 2023 Stanford University Convex Optimization Group
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14from __future__ import annotations
16from typing import Any
18import numpy as np
19import pandas as pd
22def iron_frame(frame: pd.DataFrame, rule: Any) -> pd.DataFrame:
23 """
24 The iron_frame function takes a pandas DataFrame
25 and keeps it constant on a coarser grid.
27 :param frame: The frame to be ironed
28 :param rule: The rule to be used for the construction of the grid
29 :return: the ironed frame
30 """
31 s_index = resample_index(pd.DatetimeIndex(frame.index), rule)
32 return _project_frame_to_grid(frame, s_index)
35def resample_index(index: pd.DatetimeIndex, rule: Any) -> pd.DatetimeIndex:
36 """
37 The resample_index function resamples a pandas DatetimeIndex object
38 to a lower frequency using a specified rule.
41 Note that the function does not modify the input index object,
42 but rather returns a pandas DatetimeIndex
43 """
44 series = pd.Series(index=index, data=index)
45 a = series.resample(rule=rule).first()
46 return pd.DatetimeIndex(a.values)
49def _project_frame_to_grid(frame: pd.DataFrame, grid: pd.DatetimeIndex) -> pd.DataFrame:
50 """
51 The project_frame_to_grid function projects a pandas DataFrame
52 to a coarser grid while still sharing the same index.
53 It does that by taking over values of the frame from the coarser
54 grid that are then forward filled.
55 An application would be monthly rebalancing of a portfolio.
56 E.g. on days in a particular grid we adjust the position and keep
57 it constant for the rest of the month.
59 :param frame: the frame (existing on a finer grid)
60 :param grid: the coarse grid
61 :return: a frame changing only values on days in the grid
62 """
63 sample = np.nan * frame
64 for t in grid:
65 sample.loc[t] = frame.loc[t]
66 # sample.loc[grid] = frame.loc[grid]
67 return sample.ffill()