CVXPY - Counting number of transactions in portfolio optimisation

405 views Asked by At

Given an input array of initial weights and returns for a porfolio, I'm looking to constrain the number of transactions realised during the optimisation (optimisation of overall return for example).

import cvxpy as cp
weights = cp.variable(n)
init_weights = df.initial_weights.values
return  = mu.T@weights

# I'm looking to constrain a variable 'nb_transactions'

nb_transactions = cp.sum(cp.abs(weights - init_weights) >= 0.00001)

prob = cp.Problem(cp.maximize(return), [nb_transactions <= 30])
prob.solve()

Any ideas on how I could solve this? Thanks

1

There are 1 answers

0
Uli On

Work with integer buy and sell indicator variables.

buys = cp.Variable(shape=(n,), boolean=True)
sells = cp.Variable(shape=(n,), boolean=True)

Max number of holdings constraint:

[cp.sum(buys) + cp.sum(sells) <= max_number_trades]

Setting constraint variables:

eps = 1e-5
w_trade = weights - init_weights

[-1 + eps <= w_trade - buys,
 w_trade - buys <= 0,
 -1 + eps <= -w_trade - sells,
 -w_trade - sells <= 0,
 0 <= buys + sells,
 buys + sells <= 1]

Note, that this problem is a mixed integer problem. The ECOS BB solver can deal with that, if the problem remains small. Otherwise, you will need a commercial grade optimizer.