Coverage for src/cvxmarkowitz/models/trading_costs.py: 100%
20 statements
« prev ^ index » next coverage.py v7.16.1, created at 2026-09-15 05:21 +0000
« prev ^ index » next coverage.py v7.16.1, created at 2026-09-15 05:21 +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.
14"""Model for trading costs."""
16from __future__ import annotations
18from dataclasses import dataclass
20import cvxpy as cp
21import numpy as np
23from cvxmarkowitz.model import Model
24from cvxmarkowitz.names import DataNames as D
25from cvxmarkowitz.names import ParameterName as P
26from cvxmarkowitz.types import Dimensions, Matrix, Variables
27from cvxmarkowitz.utils.fill import fill_vector
30@dataclass(frozen=True)
31class TradingCosts(Model):
32 """Model for trading costs."""
34 def __post_init__(self) -> None:
35 """Initialize trading cost parameters and previous-weights cache."""
36 self.parameter[P.POWER] = cp.Parameter(shape=(), name=P.POWER, value=1.0)
38 # initial weights before rebalancing -- keyed by D.WEIGHTS, the same name
39 # the decision variable uses, since it is the previous value of it.
40 self.data[D.WEIGHTS] = cp.Parameter(shape=self.assets, name=D.WEIGHTS, value=np.zeros(self.assets))
42 def estimate(self, variables: Variables) -> cp.Expression:
43 """Estimate trading costs for a rebalance.
45 Args:
46 variables: Optimization variables, expected to contain D.WEIGHTS.
48 Returns:
49 A convex expression representing the p-power cost of trades
50 between current and previous weights.
51 """
52 return cp.sum(
53 cp.power(
54 cp.abs(variables[D.WEIGHTS] - self.data[D.WEIGHTS]),
55 p=self.parameter[P.POWER],
56 )
57 )
59 def dimensions(self, **kwargs: Matrix) -> Dimensions:
60 """Return the number of assets the previous weights imply."""
61 return ((D.WEIGHTS, len(kwargs[D.WEIGHTS])),)
63 def update(self, **kwargs: Matrix) -> None:
64 """Update cached data values.
66 Expected keyword arguments:
67 weights: Vector of previous weights used as the trading baseline.
68 """
69 self.data[D.WEIGHTS].value = fill_vector(num=self.assets, x=kwargs[D.WEIGHTS])