Error while GARCH Modeling using Python
Question: I have a sample python code for GARCH modeling which creates a data of
randomly generated numbers. I want to replace the numbers with my own csv file
which contains a column vector, but that just doesn't work.

    
    
    import numpy as np
    from scipy import optimize
    
    r=np.array([0.945532630498276,
    0.614772790142383,
    0.834417758890680,
    0.862344782601800,
    0.555858715401929,
    0.641058419842652,
    0.720118656981704,
    0.643948007732270,
    0.138790608092353,
    0.279264178231250,
    0.993836948076485,
    0.531967023876420,
    0.964455754192395,
    0.873171802181126,
    0.937828816793698])
    
    print r
    
    f=open('main_ax.csv')
    b=f.read()
    r=np.array(b)
    print r
    def GARCH11_logL(param, r):
        omega, alpha, beta = param
        n = len(r)
        s = np.ones(n)
        for i in range(3,n):
            s[i] = omega + alpha*r[i-1]**2 + beta*(s[i-1]) # GARCH(1,1) model
        logL = -( (-np.log(s) - r**2/s).sum() )            # calculate the sum 
        return logL
    R = optimize.fmin(GARCH11_logL,np.array([.1,.1,.1]),args=(r,),full_output=1)
    print R
    print
    print("omega = %.6f\nbeta  = %.6f\nalpha = %.6f\n") % (R[0][0],R[0][2],R[0][1])
    

This program throws me the following error:

    
    
    Traceback (most recent call last):
      File "C:\Users\Gaurav\Desktop\Ram\garch_model.py", line 35, in <module>
        R = optimize.fmin(GARCH11_logL,np.array([.1,.1,.1]),args=(r,),full_output=1)
      File "C:\Python27\lib\site-packages\scipy\optimize\optimize.py", line 377, in fmin
        res = _minimize_neldermead(func, x0, args, callback=callback, **opts)
      File "C:\Python27\lib\site-packages\scipy\optimize\optimize.py", line 435, in _minimize_neldermead
        fsim[0] = func(x0)
      File "C:\Python27\lib\site-packages\scipy\optimize\optimize.py", line 285, in function_wrapper
        return function(*(wrapper_args + args))
      File "C:\Users\Gaurav\Desktop\Ram\garch_model.py", line 32, in GARCH11_logL
        s[i] = omega + alpha*r[i-1]**2 + beta*(s[i-1]) # GARCH(1,1) model
    TypeError: unsupported operand type(s) for ** or pow(): 'numpy.string_' and 'int'
    

Any help to fix this code will be really helpful.


Answer: The lines

    
    
    f=open('main_ax.csv')
    b=f.read()
    r=np.array(b)
    

create an array with a single element that is a string. You haven't converted
the contents of the file into an array of numbers.

You can replace that code with a call to
[`numpy.loadtxt`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html):

    
    
    r = np.loadtxt('main_ax.csv')
    

