Skip to content

Commit

Permalink
merged long-only and unconstrained
Browse files Browse the repository at this point in the history
  • Loading branch information
kasperjo committed Oct 23, 2023
1 parent abfba19 commit b917d94
Showing 1 changed file with 30 additions and 18 deletions.
48 changes: 30 additions & 18 deletions experiments/taming.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,28 @@
import matplotlib.pyplot as plt


def unconstrained_markowitz(inputs: OptimizationInput) -> np.ndarray:
def unconstrained_markowitz(
inputs: OptimizationInput, long_only: bool = False
) -> np.ndarray:
"""Compute the unconstrained Markowitz portfolio weights."""
n_assets = inputs.prices.shape[1]

mu, Sigma = inputs.mean.values, inputs.covariance.values

w = cp.Variable(n_assets)
c = cp.Variable()
if long_only:
w = cp.Variable(n_assets, nonneg=True)
c = cp.Variable(nonneg=True)
else:
w = cp.Variable(n_assets)
c = cp.Variable()
objective = mu @ w

chol = np.linalg.cholesky(Sigma)
constraints = [
cp.sum(w) + c == 1,
cp.norm2(chol.T @ w) <= inputs.risk_target,
]

problem = cp.Problem(cp.Maximize(objective), constraints)
problem.solve(get_solver())
assert problem.status in {cp.OPTIMAL, cp.OPTIMAL_INACCURATE}
Expand All @@ -30,21 +37,26 @@ def unconstrained_markowitz(inputs: OptimizationInput) -> np.ndarray:

def long_only_markowitz(inputs: OptimizationInput) -> np.ndarray:
"""Compute the long-only Markowitz portfolio weights."""
n_assets = inputs.prices.shape[1]

mu, Sigma = inputs.mean.values, inputs.covariance.values

w = cp.Variable(n_assets, nonneg=True)
c = cp.Variable(nonneg=True)
objective = mu @ w
constraints = [
cp.sum(w) + c == 1,
cp.quad_form(w, Sigma, assume_PSD=True) <= inputs.risk_target**2,
]
problem = cp.Problem(cp.Maximize(objective), constraints)
problem.solve(get_solver())
assert problem.status in {cp.OPTIMAL, cp.OPTIMAL_INACCURATE}
return w.value, c.value
return unconstrained_markowitz(inputs, long_only=True)


# def long_only_markowitz(inputs: OptimizationInput) -> np.ndarray:
# """Compute the long-only Markowitz portfolio weights."""
# n_assets = inputs.prices.shape[1]

# mu, Sigma = inputs.mean.values, inputs.covariance.values

# w = cp.Variable(n_assets, nonneg=True)
# c = cp.Variable(nonneg=True)
# objective = mu @ w
# constraints = [
# cp.sum(w) + c == 1,
# cp.quad_form(w, Sigma, assume_PSD=True) <= inputs.risk_target**2,
# ]
# problem = cp.Problem(cp.Maximize(objective), constraints)
# problem.solve(get_solver())
# assert problem.status in {cp.OPTIMAL, cp.OPTIMAL_INACCURATE}
# return w.value, c.value


def equal_weights(inputs: OptimizationInput) -> np.ndarray:
Expand Down

0 comments on commit b917d94

Please sign in to comment.