Search code examples
pythonif-statementsyntax-errornested-loopsiterable

Unexpected SyntaxError: invalid syntax in nested loops


Why it gives SyntaxError: invalid syntax in the second last line for jindx in xrange(1, 10):? It happens with any command I try

import numpy as np
from __future__ import division

def olsgmm(lhv, rhv, lags, wight):
    global Exxprim
    global inner
    if len(rhv[:,]) != len(lhv[:,]):
        print ("olsgmm: leftand right sides must have same number of rows. Currentlyrows are:")
        len(lhv)
        len(rhv)
    T = len(lhv[:,])
    N = len(lhv[:,1])
    K = len(rhv[:,1])
    sebv = np.zeros()
    Exxprim = np.linalg.inv((rhv.T * rhv)/T)
    bv = np.linalg.lstsq(rhv, lhv)
    if (len(weight[:,]) == 1 & len(lhv[:,1]) > 1):
        weight = weight * np.ones(len(lhv[:,1]),)
    if (len(lags[:,]) == 1 & len(lhv[:,1]) > 1):
        lags = lags * np.ones(len(lhv[:,1]),)
    if weight == -1: 
        sebv = float('nan')
        R2v = float('nan')
        R2vadj = float('nan')
        v = float('nan')
        F = float('nan')
    else:
        errv = lhv - rhv * bv
        s2 = np.mean(np.power(err, 2))
        vary = lhv - np.ones(T, 1)
        vary = np.mean(np.power(vary, 2))
        R2v = (1 - np.divide(s2, vary))
        R2adj = (1 - (np.divide(s2, vary)) * (T - 1)/(T - K)).T
        for indx in xrange(1, N + 1):
            err = errv[:,indx]
            if (weight[indx] == 0 | weight[indx] == 1):
                inner = (np.multiply(rhv, (err * np.ones(1,k))).T * (np.multiply(rhv, np.ones(1, K)))/T
                for jindx in xrange(1, 10):
                    inneradd = ([np.multiply(rhv, err) for j in xrange(1, T - jindx)] * np.ones(1, k)).T

In addition to this when I run the numpy.linalg.lstsq() in line 16, rhv and lhv are both K x N matrix (rhv first row is intercept and second row is regressor), it gives me 4 N x N array of coefficients. Does anyone know how to perform a correct joint output ls regression so as to end up with 2 K x N array of coefficients?


Solution

  • You missed out a ) on the preceding line:

    inner = (np.multiply(rhv, (err * np.ones(1,k))).T * (np.multiply(rhv, np.ones(1, K)))/T
    #       ^           2     3             4   432     2           3            4    432  ?
    

    That outer parentheses pair would be redundant however; you don't need to group a top-level expression. There are a further two pairs of redundant parentheses; the following should work just fine:

    np.multiply(rhv, err * np.ones(1, k)).T * np.multiply(rhv, np.ones(1, K)) / T
    

    Because Python allows for logical lines to span multiple physical lines of source code by enclosing them in parentheses (or square brackets or curly braces) the for line is part of the offending line as there is no closing ) found yet.

    So, rule of thumb: when you get a SyntaxError that doesn't appear to make sense, check the preceding lines for a missing closing brace.