risk parity python
时间: 2023-11-26 17:04:47 浏览: 33
Risk parity is a portfolio construction technique that aims to allocate risk equally among assets in a portfolio. Here's an example of how to implement risk parity in Python using the `cvxpy` library:
```python
import numpy as np
import cvxpy as cp
# Define asset returns
returns = np.array([[0.01, 0.05, 0.03], [0.02, 0.03, 0.01], [0.04, 0.01, 0.02]])
# Calculate asset volatilities
volatilities = np.std(returns, axis=0)
# Define covariance matrix
covariance = np.cov(returns.T)
# Define variables and constraints
weights = cp.Variable(3)
constraints = [cp.sum(weights) == 1, weights >= 0, cp.sum(cp.multiply(weights, volatilities)) == 1]
# Define objective function
portfolio_variance = cp.quad_form(weights, covariance)
objective = cp.Minimize(portfolio_variance)
# Solve problem
problem = cp.Problem(objective, constraints)
problem.solve()
# Print results
print("Optimal weights:", weights.value)
```
This code defines a 3-asset portfolio with returns specified in the `returns` array. The code then calculates the asset volatilities and covariance matrix, and defines the optimization problem using `cvxpy`. The objective function is to minimize portfolio variance, subject to constraints that the sum of weights equals 1, weights are non-negative, and the sum of weighted volatilities equals 1 (i.e. equal risk weighting). Finally, the problem is solved using `cvxpy` and the optimal weights are printed.