SyntaxError:Can't assign to function call -coding on a Financial analysis tool

Question:

def SMMA(column,N):
    for i in range(len(column)):
        if i <= N:
            SMMA(i) = np.nan()
        elif i == N + 1:
            SMMA(i) = column[:N].mean()
        else:
            SMMA(i) = (SMMA(i-1)*N + column[i])/ N

Smoothed Moving Average (SMMA) is one of my favorite financial analysis tool.It is different from the well-know Simply moving Average tool. below is the definition and above is my code, but the IDE is kept telling me syntaxError:

  File "<ipython-input-13-fdcc1fd914c0>", line 6
SMMA(i) = column[:N].mean()
^SyntaxError: can't assign to function call

Definition of SMMA:

The first value of this smoothed moving average is calculated as the simple moving average (SMA):

SUM1 = SUM (CLOSE (i), N)

SMMA1 = SUM1 / N

The second moving average is calculated according to this formula:

SMMA (i) = (SMMA1*(N-1) + CLOSE (i)) / N

Succeeding moving averages are calculated according to the below formula:

PREVSUM = SMMA (i – 1) * N

SMMA (i) = (PREVSUM – SMMA (i – 1) + CLOSE (i)) / N

Asked By: user9161038

||

Answers:

SMMA(i) is written as if calling a function. A variable can be assigned to the output of a function but it does not make sense to call a function as a variable and set it equal to a value. For example moving_average = SMMA(i) would assign a variable, moving_average, to the output of the function SMMA(i) but SMMA(i) = moving_average does not make sense. Hope I helped.
`

SMMA(i) = 4
Traceback (most recent call last):
Python Shell, prompt 5, line 1
Syntax Error: can't assign to function call: <string>, line 1, pos 0

`

Answered By: Jack

Is something like this what you had in mind?

def SMMA(column,N):
    result = np.empty(len(column))
    for i, e in enumerate(column):
        if i <= N:
            result[i] = np.nan()
        elif i == N + 1:
            result[i] = column[:N].mean()
        else:
            result[i] = (result[i-1]*N + e) / N
    return result

You can assign to a subscript like result[i] in Python.

The function isn’t going to do anything unless you return or yield a value or mutate an argument or something.

The above code generates and returns a NumPy float array, which may or may not be what you want. (If this is insufficient, please edit your question to clarify the intended use.)

Answered By: gilch

I recommend to use simple EMA calculation to achieve this.
SMMA essentially is EMA but just with different length.

For a SMMA(x) , I will do EMA(x*2-1)

SMMA EMA
1 1
2 3
3 5
4 7
5 9
6 11
7 13
8 15
9 17
10 19
11 21
12 23
13 25
14 27
15 29
16 31
17 33
Answered By: Hans Loos
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.