我试图将代码从MATLAB转换为Python,但遇到一些错误。我的代码使用scipy.optimize包中的minimum函数来最小化对数似然函数。我也尝试过从同一包中提取fmin。由于受到限制,我收到与优化步骤相关的错误消息。变量“收益”是股票市场收益的向量。任何帮助将不胜感激。
MATLAB
function param = calibrate_GARCH(returns, startingValues)
% computes maximum likelhood estimates for a GARCH(1,1) process give
% timeseries "returns" using fminsearch function
options = optimset('TolX',1e-12,'MaxFunEvals',3000,'Maxiter',3000,'Display',
'off','LargeScale','off');
param = fminsearch(@(param)computeNegLLH(param,returns), startingValues,
options);
end
% param for the given timeseries returns
sigma2 = zeros(size(returns));
omega = param(1);
alpha = param(2);
beta = param(3);
sigma2(1) = param(4);
% parameter restrictions: omega>0 alpha,beta>=0
% ensure that GARCH(1,1) process is covariance-stationary
if omega<=0 || min(alpha,beta)<0 || alpha + beta >= 1 || sigma2(1)<=0;
negLLH = intmax;
return;
end
% calculate squared returns
returns2 = returns.^2;
for t=2:length(returns)
sigma2(t)= omega + alpha*returns2(t-1) + beta*sigma2(t-1);
end
% computes (-1)xLogLikelihood for a GARCH(1,1) process with parameters
negLLH = 0.5*sum(log(sigma2) + returns2./sigma2);
end
Python 3
def computeNegLLH(param):
sigma2 = np.zeros(len(returns)); #zeros(size(returns));
omega = param[0];
alpha = param[1];
beta = param[2];
sigma2[1] = param[3];
# parameter restrictions: omega>0 alpha,beta>=0
if (omega<=0 or min(alpha,beta)<0 or alpha + beta >= 1 or sigma2[0]<=0):
negLLH = sys.maxsize;
sys.exit();
# calculate squared returns
returns2 = returns**2;
for t in range(1,len(returns)):
sigma2[t]= omega + alpha*returns2[t-1] + beta*sigma2[t-1];
# computes (-1)xLogLikelihood for a GARCH(1,1) process with parameters
negLLH = 0.5*sum(log(sigma2) + returns2/sigma2);
return negLLH
res = minimize(fun = computeNegLLH, x0 = startingValues, method = 'Nelder-Mead', tol = None, options = {'xtol': 1e-8, 'disp': True,'maxiter': 2000})