'numb.ndarray' object is not callable

mit matplotlib, NumPy, pandas, SciPy, SymPy und weiteren mathematischen Programmbibliotheken.
Antworten
YPython1
User
Beiträge: 26
Registriert: Mittwoch 24. Februar 2021, 21:06

Code: Alles auswählen


def weights_matrix(Cov):
    #   Creating a random number seed that adds up to 1 
    #   Crating of gthe inital guess
    w = np.transpose(np.array(np.random.dirichlet(np.ones(len(Cov)), size =1 )))
    return w

#   Defining the Optimization Values
def Optimization_Values(Expect , Cov, r_f, w):
    #   Expected return of the Portfolio
    Mu = np.sum(np.transpose(w) * Expect.values)
    #   Standard deviation of the Portfolio
    Std = np.sqrt(np.matmul(np.matmul(np.transpose(w),Cov.values), w))  
    #   Sharpe Ratio Formula
    Sharpe_Ratio = (Mu-r_f)/Std
    
    return Mu, Std, Sharpe_Ratio

def Optimization_objective (Expect , Cov, r_f, w):
    #   Expected return of the Portfolio
    Mu = np.sum(np.transpose(w) * Expect.values)
    #   Standard deviation of the Portfolio
    Std = np.sqrt(np.matmul(np.matmul(np.transpose(w),Cov.values), w))  
    #   Sharpe Ratio Formula
    Sharpe_Ratio = (Mu-r_f)/Std
    
    return Sharpe_Ratio 

#   Defining the Iptimization objective
def objective (Expect , Cov, r_f, w):
    return -Optimization_objective(Expect , Cov, r_f, w)
    
#   Defining the Constraint w = 1
def constraint(w):
    PorV = 1    #   Protfolio Restriction 1
    for i in range(len(w)):
        PorV = PorV - w[i]
    return PorV

    

#%%###########################################################################
#   Main calling of the functions
##############################################################################

cons = ({'type':'eq', 'fun':constraint})
w = weights_matrix(Cov)
Mu, Std, Sharpe_Ratio = Optimization_Values(Expect , Cov, r_f, w)
print(objective(Expect , Cov,  r_f, w))
sol = minimize(objective(Expect , Cov,  r_f, w), w, method='SLSQP', constraints = cons, options={'disp':True})
#Weights, PortRet = MeanVarinaceOpt (returns, Expect, Var, Cov, Corr, r_f)

Den Fehler den ich bekomme entsteht immer bei minimize (habe es richtig importiert) auch die Werte Excpect usw sind richtig bestimmt.

Jetzt bekomme ich aber immer folgenden Fehler:
Bin damit leider überfordert und verstehe nicht so ganz was der Fehler ist habe es auch schon mit x0 = [1,1,1,1,1] ausprobiert kommt der selbe Fehler. Wenn mir jemand Helfen könnte wer ich sehr dankbar

Code: Alles auswählen

Traceback (most recent call last):

  File "", line 122, in <module>
    sol = minimize(objective(Expect , Cov,  r_f, w), x0 = [1,1,1,1,1], method='SLSQP', constraints = cons, options={'disp':True})

  File "lib/python3.8/site-packages/scipy/optimize/_minimize.py", line 625, in minimize
    return _minimize_slsqp(fun, x0, args, jac, bounds,

  File "anaconda3/lib/python3.8/site-packages/scipy/optimize/slsqp.py", line 368, in _minimize_slsqp
    sf = _prepare_scalar_function(func, x, jac=jac, args=args, epsilon=eps,

  File "anaconda3/lib/python3.8/site-packages/scipy/optimize/optimize.py", line 261, in _prepare_scalar_function
    sf = ScalarFunction(fun, x0, args, grad, hess,

  File "anaconda3/lib/python3.8/site-packages/scipy/optimize/_differentiable_functions.py", line 76, in __init__
    self._update_fun()

  File "anaconda3/lib/python3.8/site-packages/scipy/optimize/_differentiable_functions.py", line 166, in _update_fun
    self._update_fun_impl()

  File "/anaconda3/lib/python3.8/site-packages/scipy/optimize/_differentiable_functions.py", line 73, in update_fun
    self.f = fun_wrapped(self.x)

  File "anaconda3/lib/python3.8/site-packages/scipy/optimize/_differentiable_functions.py", line 70, in fun_wrapped
    return fun(x, *args)

TypeError: 'numpy.ndarray' object is not callable
rogerb
User
Beiträge: 878
Registriert: Dienstag 26. November 2019, 23:24

Hallo YPython1,
YPython1 hat geschrieben: Dienstag 18. Mai 2021, 18:57

Code: Alles auswählen

sol = minimize(objective(Expect , Cov,  r_f, w), w, method='SLSQP', constraints = cons, options={'disp':True})
scipy.optimize.minimize ?

Laut Doku soll der erste Parameter ein 'callable' also eine *Funktion* sein. Du übergibst aber den *Rückgabewert der Funktion* in dem du die Funktion aufrufst.
Die Doku enthält auch ein Beispiel

https://docs.scipy.org/doc/scipy/refere ... imize.html
YPython1
User
Beiträge: 26
Registriert: Mittwoch 24. Februar 2021, 21:06

Danke Ich weiß jetzt was das Problem ist allerdings bekomme ich es nicht hin folgenden Teil variable zu gestalten:
Hierbei müsste:

Code: Alles auswählen

w ja wie folgt aussehen

w1 = w[0]
w2 = w[1]
     .
     .
 Da es sich hierbei aber um matrix Multiplikation handelt bekomme ich es irgendwie nicht die Werte Variabel zu belassen.

Code: Alles auswählen

def Optimization_objective (Expect , Cov, r_f):
    
    
    #   Expected return of the Portfolio
    Mu = np.sum(np.transpose(w) * Expect.values)
    #   Standard deviation of the Portfolio
    Std = np.sqrt(np.matmul(np.matmul(np.transpose(w),Cov.values), w))  
    #   Sharpe Ratio Formula
    Sharpe_Ratio = (Mu-r_f)/Std
    
    return Sharpe_Ratio 

#   Defining the Iptimization objective
def objective (Expect , Cov,  r_f):
    return -Optimization_objective(Expect , Cov,  r_f)
YPython1
User
Beiträge: 26
Registriert: Mittwoch 24. Februar 2021, 21:06

Bzw. überhaupt zu einem Ergebnis zukommen bekomme ich nicht hin.
rogerb
User
Beiträge: 878
Registriert: Dienstag 26. November 2019, 23:24

Wie rufst du die minimize Funktion denn jetzt auf.

Ich bin leider kein ML Experte und kann auch nur in die Doku schauen.

Kannst du das komplette Programm posten?

Ich würde an deiner Stelle mal mit einem einfachen Beispiel anfangen und es dann auf komplexere Probleme übertragen.
YPython1
User
Beiträge: 26
Registriert: Mittwoch 24. Februar 2021, 21:06

Code: Alles auswählen

#%%############################################################################
#   Import of packages


import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os
from scipy.optimize  import minimize

#%%###########################################################################
#   Import of data and Caluclation of Key Figures for Mean Opt.
##############################################################################

#   Opening data from Drobbox individual by users path
def DataImport():

    pfad =os.path.abspath(".")          #   find path name of this python data; to find the diamonds.csv file
    slices = pfad.rfind("/")
    pfad = pfad[0:slices] + "/Data"
    data = pd.read_excel(pfad + '/DataSet.xlsx', header = 2)   #    import data
    
    #returns = data.pct_change(1)    # returns of the ETF's
    returns = np.log(data)-np.log(data.shift(1))    # log returns of the ETF's
    returns = returns[1:][:]
    
    return (data, returns)


def KeyFigures (returns):

    #   Computing Mean of each ETF
    meanOfETF = returns.mean()
    print(meanOfETF)
    
    ###### Computing Variance of each ETF
    varOfETF = returns.var()
    print(varOfETF)
    
    #   Computing Covariance 
    covOfETF = returns.cov()
    print(covOfETF)
    
    #   Computing correlation 
    corrOfETF = returns.corr()
    print(corrOfETF)
    
    #   Risk Free Rate
    r_f = np.mean(returns["Moneymarket ETF"])
    print(r_f)
     
    
    return (meanOfETF, varOfETF, covOfETF, corrOfETF, r_f)

#%%###########################################################################
#   Mean Varianz optimization
##############################################################################

def weights_matrix(Cov):
    #   Creating a random number seed that adds up to 1 
    #   Crating of gthe inital guess
    #w = np.transpose(np.array(np.random.dirichlet(np.ones(len(Cov)), size =1 )))
    w = (np.ones(Cov.shape[0]))*(1/Cov.shape[0])
    return w

#   Defining the Optimization Values
def Optimization_Values(Expect , Cov, r_f):
    #   Expected return of the Portfolio
    Mu = np.sum(np.transpose(x0) * Expect.values)
    #   Standard deviation of the Portfolio
    Std = np.sqrt(np.matmul(np.matmul(np.transpose(x0),Cov.values), x0))  
    #   Sharpe Ratio Formula
    Sharpe_Ratio = (Mu-r_f)/Std
    
    return Mu, Std, Sharpe_Ratio

def Optimization_objective (w1):
    w = []
    for i in range(len(Cov)):
        w = w1[i]
    
    #   Expected return of the Portfolio
    Mu = np.sum(np.transpose(w) * Expect.values)
    #   Standard deviation of the Portfolio
    Std = np.sqrt(np.matmul(np.matmul(np.transpose(w),Cov.values), w))  
    #   Sharpe Ratio Formula
    Sharpe_Ratio = (Mu-r_f)/Std
    
    return (Mu-r_f)/Std

#   Defining the Iptimization objective
def objective (w1):
    return -Optimization_objective(Expect , Cov,  r_f)
    
#   Defining the Constraint w = 1
def constraint(w):
    PorV = 1    #   Protfolio Restriction 1
    for i in range(len(w)):
        PorV = PorV - w[i]
    return PorV

#   Defining the Bounds w between 0 and 1 
#   No neagtive bound and non levarge bound
def bounds(w):
    b = (0,1)
    bnds = (b,)* len(w)
    
    return bnds

#%%###########################################################################
#   Main calling of the functions
##############################################################################

#   def main():
data, returns = DataImport()
Expect , Var, Cov, Corr, r_f = KeyFigures(returns)

x0 = weights_matrix(Cov)
cons = ({'type':'eq', 'fun':constraint})
bnds = bounds(x0)

Mu, Std, Sharpe_Ratio = Optimization_Values(Expect , Cov, r_f)
print(objective)
sol = minimize(objective, x0, method='SLSQP',\
               bounds = bnds, constraints = cons, options={'disp':True})
rogerb
User
Beiträge: 878
Registriert: Dienstag 26. November 2019, 23:24

Ist das überhaupt lauffähig?

Code: Alles auswählen

def Optimization_objective (w1):
...
...
return -Optimization_objective(Expect , Cov,  r_f)
Die Funktion hat einen Eingangsparameter, du übergibst aber drei. Von daher dürfte das so eigentlich gar nicht lauffähig sein

Code: Alles auswählen

#   Defining the Iptimization objective
def objective (w1):
    return -Optimization_objective(Expect , Cov,  r_f)
Hier gibt es den Eingangsparameter w1, der wird aber nicht in der Funktion verwendet. das gibt zwar keinen Fehler, macht aber auch keinen Sinn.

Code: Alles auswählen

def Optimization_objective (w1):
    w = []
    for i in range(len(Cov)):
        w = w1[i]
Hier wird w immer wieder mit einem anderen Wert überschrieben. Am Ende steht in w wahrscheinlich nur ein numerischer Wert. Aber anscheinend wolltest du w als Liste erzeugen.
Wenn man

Code: Alles auswählen

w = w1[i]
umwandelt in

Code: Alles auswählen

w[i] = w1[i]
könnte es vielleicht Sinn machen
YPython1
User
Beiträge: 26
Registriert: Mittwoch 24. Februar 2021, 21:06

es funktioniert alles bis auf die Optimierung, das da was mit der Funktion schief läuft ist mir bewusst weiß allerdings nicht genau wie ich das beheben kann. Mit w = w1 hat es schonmal nicht funktioniert. Die Sache ist ich kenn einfach die länge der x[] Faktoren bei der Optimierung nicht, bzw. die können je nach input variieren. Weiterhin werden die werte in der Funktion vorher berechnet (Expect_return, Cov usw.) w soll die Matrix sein die Variable verändert werden kann und dann je nach länge vom Optimiert werden soll.
Benutzeravatar
kbr
User
Beiträge: 1487
Registriert: Mittwoch 15. Oktober 2008, 09:27

@YPython1: Ohne zu verstehen, *was* du da machst: der Code läuft nur, da die Funktionen, die rogerb genannt hat, überhaupt nicht aufgerufen werden – und weil 'def main()' auskommentiert ist und somit die dort angelegten Bezeichner anderen Funktionen global zur Verfügung stehen. Insgesamt ist das recht unsauber und die kruden Bezeichner erleichtern ein Verständnis nicht gerade.

Weiter sind Funktionen wie diese ungeschickt

Code: Alles auswählen

>>> def constraint(w):
...     PorV = 1    #   Protfolio Restriction 1
...     for i in range(len(w)):
...         PorV = PorV - w[i]
...     return PorV
da man dies auch so schreiben könnte

Code: Alles auswählen

>>> 1 - sum(w)
Beim 'DataImport' werden die Daten zweimal logarithmiert und returns ist auch ein verwirrender Name:

Code: Alles auswählen

>>> data_log = data.apply(np.log)
>>> result = (data_log - data_log.shift(1))[1:]
Vermutlich gibt es noch mehr solcher Baustellen und ich nehme an, dass Du das auch nicht alles selbst geschrieben hast, sondern auf bestehenden Code aufbaust. Das kann bei dieser Codebasis dann schnell frustrierend werden.
YPython1
User
Beiträge: 26
Registriert: Mittwoch 24. Februar 2021, 21:06

Der Code ist an manchen Stellen vielleicht nicht optimal programmiert bin aber auch noch ein relativer Anfänger in Python.
Das eigentliche Problem des Codes liegt aber aufjedenfall in folgendem teil das dort die Matrix nicht richtig als Funktion übergeben wird.
Expect.values ist eine Matrix aus nx1
Cov.Values ist eine Matrix aus nxn

w soll auch genau so lang sein wie Expect.values Matrix also nx1

Code: Alles auswählen

def Optimization_objective (w1):
    w = []
    for i in range(len(Cov)):
        w[i] = w1[i]
    
    #   Expected return of the Portfolio
    Mu = np.sum(np.transpose(w) * Expect.values)
    #   Standard deviation of the Portfolio
    Std = np.sqrt(np.matmul(np.matmul(np.transpose(w),Cov.values), w))  
    #   Sharpe Ratio Formula
    Sharpe_Ratio = (Mu-r_f)/Std

return Sharpe_Ratio

#   Defining the Iptimization objective
def objective (w1):
    return -Optimization_objective(w1)
    
    
    sol = minimize(objective, x0, method='SLSQP',\
               bounds = bnds, constraints = cons, options={'disp':True})
rogerb
User
Beiträge: 878
Registriert: Dienstag 26. November 2019, 23:24

Mit w = w1 hat es schonmal nicht funktioniert.
Ja,

versuch mal:

Code: Alles auswählen

w = w1[:len(Cov)]
Du hattest ja auch geschrieben, das Cov eine nxn Matrix ist. len() wird also quasi n zurückgeben.
in w wird dann ein Teil von w1 mit der Länge n gespeichert.

Ich kann aber eigentlich nur raten. Ich habe ja keinen Zugriff auf die verwendeten Daten und kann es daher auch nicht ausprobieren bzw. reparieren.
Wenn es nicht funktioniert, würden die Fehlermeldungen auch schon viel helfen.
YPython1
User
Beiträge: 26
Registriert: Mittwoch 24. Februar 2021, 21:06

Vielen dank es ist jetzt zumindest mal durchgelaufen ob es jetzt das richtige Ergebnis ausgeworfen hat muss ich nochmal überprüfen. Aber danke du hast mir wirklich sehr geholfen
Antworten