I have created a set of functions that call each other to price options. One of the functions runs for quite a while to optimize some parameters (using Nelder Mead). Within this function, a value is calculated, that I would like to use in some other functions, but I do not want to pass it out through the return statement. I thought using global var would be perfect.
Now, the weird part: When I load the functions I wrote as a package via import *
, I cannot access the global var the one function creates. If I take the script with the function definitions, run it to define the functions in my Python console, and then call the functions, the global var construction works fine. What might be the issue and why does it make a difference whether I load/define the functions as a package or 'manually'?
Error when loading as package: NameError: name 'h_out' is not defined
.
global h_out
h_out=None
import hngoption
prices = timeseries[data.Date[i]:].head(30)
output = hngoption.params(prices)
params() calls function LogLike() as part of its computations which contains:
def LogLike(B, r):
# (...)
for i in range(N - 3, -1, -1):
h[i] = B[0] + B[2] * h[i + 1] + B[1] * pow(Z[i + 1] - B[3] * sqrt(h[i + 1]), 2)
Z[i] = (ret[i] - r - B[4] * h[i]) / (h[i] ** 0.5)
L[i] = -log(h[i]+ 0.000000000000001) - (ret[i] ** 2) / h[i]
LogL = VecSum(L)
global h_out #IMPORTANT PART
h_out = h[0]
if ((B[0] < 0) | (B[1] < 0) | (B[2] < 0) | (B[3] < 0) | (B[4] < 0)): # (B[2]+B[1]*pow(B[3],2)>=1))
return 1e50
else:
return -LogL # Minimize -Log-Like(Beta)
Full LogLike function:
def LogLike(B, r):
N = len(timeseries) #timeseries is a global var
# Calculate S&P500 returns
ret = [0.0] * (N - 1)
for i in range(0, N - 1):
ret[i] = (log(timeseries.ix[i] / timeseries.ix[i + 1]))
Variance = VecVar(ret)
h = [0 * i for i in range(N - 1)]
Z = [0 * i for i in range(N - 1)]
L = [0 * i for i in range(N - 1)]
# Construct GARCH(1,1) process by working back in time
h[N - 2] = Variance
Z[N - 2] = (ret[N - 2] - r - B[4] * h[N - 2]) / h[N - 2] ** 0.5
L[N - 2] = -log(h[N - 2]) - (ret[N - 2] ** 2) / h[N - 2]
for i in range(N - 3, -1, -1):
h[i] = B[0] + B[2] * h[i + 1] + B[1] * pow(Z[i + 1] - B[3] * sqrt(h[i + 1]), 2)
Z[i] = (ret[i] - r - B[4] * h[i]) / (h[i] ** 0.5)
L[i] = -log(h[i]+ 0.000000000000001) - (ret[i] ** 2) / h[i]
LogL = VecSum(L)
global h_out #IMPORTANT PART
h_out = h[0]
if ((B[0] < 0) | (B[1] < 0) | (B[2] < 0) | (B[3] < 0) | (B[4] < 0)): # (B[2]+B[1]*pow(B[3],2)>=1))
return 1e50
else:
return -LogL # Minimize -Log-Like(Beta)