I'm trying to solve an optimization problem in finance to obtain the weights of each equity in the portfolio, which Maximizes the portfolio's expected return and Minimizes the portfolio's Value at Risk (VaR). I'm currently trying to model this with one objective function instead of multi-objective optimization models. Hence, this can be achieved by defining a maximization function that has two components; First, the expected return of the portfolio (with positive (+1) coefficient) and, second, the VaR of the portfolio (with negative (-1) coefficient). So the model will be like this:
Maximize: expected_return - VaR
About one and a half years ago, I wrote the Python code for the first component (Maximize: expected_return) using the Gekko library, and now I'm also trying to include the second component. But the problem I encountered was this: I had to sort a pd.Series and pick a value at a specific index of the sorted series to calculate the VaR of the portfolio; But since all of the values of this series include the Gekko variables, then sorting can't be done! I want to dig deeper by sharing the code and the problem.
First of all, let's take a look at the objective functions:
import pandas as pd
import numpy as np
def expected_return(x,Array):
res = 0
for j in range(len(Array)):
res += x[j] * qw.log10(Array[j])
return res
def VaRfunc(df:pd.DataFrame, weights:np.ndarray, initial_investment:int, alpha:float):
"""
Calculating the Value at Risk of the portfolio with the given weights
Params
------
df: pd.DataFrame
dataframe of adjusted close prices
weights: np.ndarray
given weights of each equity in the portfolio
initial_investment: int
initial investment
alpha: float
the confidence level for calculating the VaR of the portfolio
Returns
------
VaR: float
value at risk of the portfolio
"""
def ScenarioMaker(x):
"""
Helper function for mapSenario
Help
----
x[0]: last close price
x[1]: close price i
x[2]: close price i-1
"""
if isinstance(x[0], float):
return (x[2] * x[1])/x[0]
else:
pass
def mapSenario(series:pd.Series):
"""
This function Should be used inside the df.apply as
function.
params
------
series: pd.Series
each column of DataFrame
Returns
-------
Calculated Scenarios for each column of the given DataFrame
through df.apply
"""
last_close = series.iloc[-1].repeat(len(series))
return list(map(ScenarioMaker, zip(series.shift(), series , last_close)))
def mapPortfolioValue(series, df, weights, initial_investment):
"""
This function should be passed as a function of df.apply which df is the
calculated scenarios dataframe through the `mapSenario` function.
Params
------
series: pd.Series
each passed series through df.apply
df: pd.DataFrame
dataframe of adjusted Close Prices
weights: np.array
weights of each equity in the portfolio
initial_investment: int
initial investment
Returns
-------
pd.Series of the portfolio value **for each given series!**
"""
idx = df.columns.tolist().index(series.name)
last_close = df.iloc[-1,idx]
return list(map(lambda x: (initial_investment*weights[idx]*x)/last_close, series))
scenarios = df.apply(mapSenario)
portValue = (scenarios.apply(mapPortfolioValue, args=[df, weights, initial_investment])).sum(axis=1).iloc[1:].reset_index(drop=True)
sortedLoss = (initial_investment-portValue).sort_values(ascending=False).reset_index(drop=True)
if int((1-alpha) * len(sortedLoss)) == ((1-alpha) * len(sortedLoss)):
VaR = sortedLoss[int((1-alpha) * len(sortedLoss)) - 1]
else:
VaR = (sortedLoss[int((1-alpha) * len(sortedLoss)) - 1] + sortedLoss[int((1-alpha) * len(sortedLoss))])/2
return VaR
The first component is the expected_return function, and the second is VaRfunc. The problem arises in the second component, where I'm trying to sort a pd.Series object named sortedLoss. To complete the optimization code, I've to define my GEKKO model like this:
from gekko import GEKKO
predicted_returns = np.array([1.00046482, 1.0002218 , 1.00037122, 1.00089297, 1.00048257, 1.00040968, 1.00099596, 0.99995046, 0.9995493 , 1.00043154])
close_data = pd.read_csv("adj_close.csv" , index_col=0)
nd = 10
qw = GEKKO(remote=False)
x = qw.Array(qw.Var,nd,value=1/nd,lb=0,ub=1)
qw.Equation(sum(x) == 1)
qw.Maximize(expected_return( x,
predicted_returns)
- VaRfunc(close_data,
x,
10_000,
0.99))
qw.solve(disp=False)
After running the code, I get this:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
c:\Users\Shayan\Desktop\optimization_test.py in <cell line: 149>()
146 x = qw.Array(qw.Var,nd,value=1/nd,lb=0,ub=1)
147 qw.Equation(sum(x) == 1)
149 qw.Maximize(Log_Caculator( x,
150 predicted_returns)
151
--> 152 - VaRfunc(close_data,
153 x,
154 10_000,
155 0.99))
156 qw.solve(disp=False)
c:\Users\Shayan\Desktop\optimization_test.py in VaRfunc(df, weights, initial_investment, alpha)
131 scenarios = df.apply(mapSenario)
132 portValue = (scenarios.apply(mapPortfolioValue, args=[df, weights, initial_investment])).sum(axis=1).iloc[1:].reset_index(drop=True)
--> 133 sortedLoss = (initial_investment-portValue).sort_values(ascending=False).reset_index(drop=True)
134 if int((1-alpha) * len(sortedLoss)) == ((1-alpha) * len(sortedLoss)):
135 VaR = sortedLoss[int((1-alpha) * len(sortedLoss)) - 1]
File c:\Users\Shayan\Anaconda3\envs\Python3.10\lib\site-packages\pandas\util\_decorators.py:311, in deprecate_nonkeyword_arguments.<locals>.decorate.<locals>.wrapper(*args, **kwargs)
305 if len(args) > num_allow_args:
306 warnings.warn(
307 msg.format(arguments=arguments),
308 FutureWarning,
309 stacklevel=stacklevel,
310 )
--> 311 return func(*args, **kwargs)
File c:\Users\Shayan\Anaconda3\envs\Python3.10\lib\site-packages\pandas\core\series.py:3526, in Series.sort_values(self, axis, ascending, inplace, kind, na_position, ignore_index, key)
3524 # GH 35922. Make sorting stable by leveraging nargsort
3525 values_to_sort = ensure_key_mapped(self, key)._values if key else self._values
-> 3526 sorted_index = nargsort(values_to_sort, kind, bool(ascending), na_position)
3528 result = self._constructor(
3529 self._values[sorted_index], index=self.index[sorted_index]
3530 )
3532 if ignore_index:
File c:\Users\Shayan\Anaconda3\envs\Python3.10\lib\site-packages\pandas\core\sorting.py:417, in nargsort(items, kind, ascending, na_position, key, mask)
415 non_nans = non_nans[::-1]
416 non_nan_idx = non_nan_idx[::-1]
--> 417 indexer = non_nan_idx[non_nans.argsort(kind=kind)]
418 if not ascending:
419 indexer = indexer[::-1]
File c:\Users\Shayan\Anaconda3\envs\Python3.10\lib\site-packages\gekko\gk_operators.py:25, in GK_Operators.__len__(self)
24 def __len__(self):
---> 25 return len(self.value)
File c:\Users\Shayan\Anaconda3\envs\Python3.10\lib\site-packages\gekko\gk_operators.py:144, in GK_Value.__len__(self)
143 def __len__(self):
--> 144 return len(self.value)
TypeError: object of type 'int' has no len()
I put the adj_close.csv data in my google drive; feel free to test the code using the given data. So as you can see, there's a problem in sorting the
(initial_investment-portValue) (which is a pd.Series object), and I guess the root of the problem is where (initial_investment-portValue) contains the Gekko variables, and this causes conflict when I try to sort that series! After this, I gave up on sorting and tried to get the maximum value of the series, but I got the same error. I guess getting the maximum value also uses the len function! So I'm stuck in this phase, and I need help.
PS: In addition to the adj_close.csv file, I put the complete codes in the link referred above, So you don't need to copy all this stuff.