Convert Absolute-Value Penalty to Linear Program Constraints
Math & Bit ManipulationAuto-graded · 22 test casesLast updated
Transform a portfolio optimization model with absolute-value transaction costs into standard linear programming form using auxiliary variables.
You are building a portfolio optimizer that must be solved by a standard linear programming solver. The original formulation maximizes expected profit minus transaction costs:
maximize: sum(alpha[i] * h[i]) - sum(c[i] * |h[i] - h0[i]|)
subject to:
A * h = b
lower[i] <= h[i] <= upper[i] for all i
Where:
his the vector of target holdings (decision variables)h0is the vector of current holdings (fixed)alpha[i]is the expected return coefficient for asset ic[i]is the nonnegative transaction cost per unit traded for asset iA * h = brepresents linear equality constraints (e.g., budget or sector constraints)lowerandupperare box bounds on each holding
Standard LP solvers cannot handle absolute values directly. Your task is to reformulate this problem by introducing auxiliary variables and converting all constraints to linear form.
Return a dictionary containing the complete LP formulation with these keys:
"sense": either"maximize"or"minimize""variable_names": list of variable names as strings"objective": list of objective coefficients (same order as variable_names)"equalities": list of equality constraint coefficient rows"equality_rhs": list of right-hand sides for equality constraints"inequalities": list of inequality constraint coefficient rows (all in <= form)"inequality_rhs": list of right-hand sides for inequality constraints"inequality_names": list of descriptive names for each inequality"lower_bounds": list of lower bounds for each variable (useNonefor unbounded)"upper_bounds": list of upper bounds for each variable (useNonefor unbounded)"equivalence": a string explaining why the auxiliary variables equal the absolute values at optimality
Name the original variables h_0, h_1, ..., h_{n-1} and the auxiliary variables u_0, u_1, ..., u_{n-1}.
For each asset i, name the two inequalities buy_trade_i and sell_trade_i.
Constraints
- All input lists are non-empty and have consistent dimensions
c[i] >= 0for all iAhas shape(m, n)wheren = len(alpha)len(h0) = len(c) = len(lower) = len(upper) = len(alpha)len(b) = len(A)- All numeric inputs are valid floats or integers
Examples
Example 1
Input: convert_absolute_penalty_to_lp([0.1, 0.2], [1, 2], [0.01, 0.03], [[1, 1]], [3], [0, 0], [3, 3])
Output: {'sense': 'maximize', 'variable_names': ['h_0', 'h_1', 'u_0', 'u_1'], 'objective': [0.1, 0.2, -0.01, -0.03], 'equalities': [[1, 1, 0, 0]], 'equality_rhs': [3], 'inequalities': [[1, 0, -1, 0], [-1, 0, -1, 0], [0, 1, 0, -1], [0, -1, 0, -1]], 'inequality_rhs': [1, -1, 2, -2], 'inequality_names': ['buy_trade_0', 'sell_trade_0', 'buy_trade_1', 'sell_trade_1'], 'lower_bounds': [0, 0, 0, 0], 'upper_bounds': [3, 3, None, None], 'equivalence': 'u_i = abs(h_i - h0_i) at every optimum because c_i >= 0; if c_i = 0, an optimal solution can be tightened to equality without changing the objective or feasibility.'}
Example 2
Input: convert_absolute_penalty_to_lp([2, -1, 0.5], [0, 1, -2], [1, 0, 2], [[1, 0, 1], [0, 1, 1]], [1, -1], [-2, -1, -3], [2, 4, 5])
Output: {'sense': 'maximize', 'variable_names': ['h_0', 'h_1', 'h_2', 'u_0', 'u_1', 'u_2'], 'objective': [2, -1, 0.5, -1, 0, -2], 'equalities': [[1, 0, 1, 0, 0, 0], [0, 1, 1, 0, 0, 0]], 'equality_rhs': [1, -1], 'inequalities': [[1, 0, 0, -1, 0, 0], [-1, 0, 0, -1, 0, 0], [0, 1, 0, 0, -1, 0], [0, -1, 0, 0, -1, 0], [0, 0, 1, 0, 0, -1], [0, 0, -1, 0, 0, -1]], 'inequality_rhs': [0, 0, 1, -1, -2, 2], 'inequality_names': ['buy_trade_0', 'sell_trade_0', 'buy_trade_1', 'sell_trade_1', 'buy_trade_2', 'sell_trade_2'], 'lower_bounds': [-2, -1, -3, 0, 0, 0], 'upper_bounds': [2, 4, 5, None, None, None], 'equivalence': 'u_i = abs(h_i - h0_i) at every optimum because c_i >= 0; if c_i = 0, an optimal solution can be tightened to equality without changing the objective or feasibility.'}
Example 3
Input: convert_absolute_penalty_to_lp([1], [4], [0], [], [], [0], [10])
Output: {'sense': 'maximize', 'variable_names': ['h_0', 'u_0'], 'objective': [1, 0], 'equalities': [], 'equality_rhs': [], 'inequalities': [[1, -1], [-1, -1]], 'inequality_rhs': [4, -4], 'inequality_names': ['buy_trade_0', 'sell_trade_0'], 'lower_bounds': [0, 0], 'upper_bounds': [10, None], 'equivalence': 'u_i = abs(h_i - h0_i) at every optimum because c_i >= 0; if c_i = 0, an optimal solution can be tightened to equality without changing the objective or feasibility.'}
Hints
Hint 1
Introduce one auxiliary variable u_i for each |h_i - h0_i| term, and add it to the objective with an appropriate coefficient.
Hint 2
To enforce u_i >= |h_i - h0_i|, write two linear inequalities: one for u_i >= h_i - h0_i and another for u_i >= -(h_i - h0_i).
Hint 3
Because the cost coefficients are nonnegative and we are maximizing, the solver will naturally push each u_i down to exactly |h_i - h0_i| at the optimum.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is eliminating the absolute value function |h_i - h0_i| from the objective. We introduce auxiliary variables to represent the magnitude of each trade.
For each asset i, we add a new nonnegative variable u_i intended to represent |h_i - h0_i|. To enforce this relationship using only linear constraints, we note that:
u_i >= h_i - h0_i(handles the case when we buy: h_i > h0_i)u_i >= -(h_i - h0_i)(handles the case when we sell: h_i < h0_i)
These two inequalities together ensure u_i >= |h_i - h0_i|.
In the objective, we replace -c[i] * |h_i - h0_i| with -c[i] * u_i. Because we are maximizing and c[i] >= 0, the optimizer has incentive to minimize u_i. The constraints force u_i to be at least |h_i - h0_i|, so at optimality, u_i will be driven down to exactly |h_i - h0_i| (unless c[i] = 0, in which case the objective doesn't care, but we can still choose u_i to equal the absolute value without affecting feasibility or objective value).
The complete transformation:
- Double the number of variables:
h_0, ..., h_{n-1}, u_0, ..., u_{n-1} - Extend the objective: original alpha coefficients for h variables, then
-c[i]for each u variable - Extend equality constraints: pad each row with n zeros for the u variables
- Add 2n inequality constraints: two per asset to bound u_i from below
- Set bounds: original bounds for h variables,
[0, infinity)for u variables
Complexity
- Time: O(n + m*n) where n is the number of assets and m is the number of equality constraints. We build O(n) inequality rows and extend m equality rows.
- Space: O(n + m*n) to store the reformulated constraint matrices.
Solution
from typing import List, Dict
def convert_absolute_penalty_to_lp(alpha: List[float], h0: List[float], c: List[float], A: List[List[float]], b: List[float], lower: List[float], upper: List[float]) -> Dict[str, object]:
n = len(alpha)
m = len(A)
names = [f"h_{i}" for i in range(n)] + [f"u_{i}" for i in range(n)]
objective = list(alpha) + [-value for value in c]
equalities = []
for row in A:
equalities.append(list(row) + [0] * n)
equality_rhs = list(b)
inequalities = []
inequality_rhs = []
inequality_names = []
# u_i >= h_i - h0_i, represented as h_i - u_i <= h0_i.
# u_i >= h0_i - h_i, represented as -h_i - u_i <= -h0_i.
for i in range(n):
row = [0] * (2 * n)
row[i] = 1
row[n + i] = -1
inequalities.append(row)
inequality_rhs.append(h0[i])
inequality_names.append(f"buy_trade_{i}")
row = [0] * (2 * n)
row[i] = -1
row[n + i] = -1
inequalities.append(row)
inequality_rhs.append(-h0[i])
inequality_names.append(f"sell_trade_{i}")
variable_lower = list(lower) + [0] * n
variable_upper = list(upper) + [None] * n
return {
"sense": "maximize",
"variable_names": names,
"objective": objective,
"equalities": equalities,
"equality_rhs": equality_rhs,
"inequalities": inequalities,
"inequality_rhs": inequality_rhs,
"inequality_names": inequality_names,
"lower_bounds": variable_lower,
"upper_bounds": variable_upper,
"equivalence": "u_i = abs(h_i - h0_i) at every optimum because c_i >= 0; if c_i = 0, an optimal solution can be tightened to equality without changing the objective or feasibility."
}