Home > Back-end >  TypeError: unsupported operand type(s) for
TypeError: unsupported operand type(s) for

Time:04-16

I am trying to create a 10-period Exponential Moving Average for stock prices. i.e. calculating average of last 10 stock prices.

To achieve this I wrote a function, but it is giving most unexpected of errors.

import numpy as np
import pandas as pd

def calc_ema(prices, window, smoothing=2):
    ema = [sum(prices[:window])/window]
    for price in prices[window:]:
        ema.append((price*(smoothing/(1 window))) ema[-1]*(1-(smoothing/(1 window))))
        return ema
   
data = {'Price':[120, 100, 108, 112, 109, 131, 125, 122, 115, 119, 124, 137, 141, 139, 136]}
df=pd.DataFrame(data)

Dema = calc_ema(df,10)
print (Dema)

When the execution goes to:

ema = [sum(prices[:window])/window]

It gives error:

TypeError: unsupported operand type(s) for  : 'int' and 'str'

CodePudding user response:

Changing prices to prices.loc[:, 'Price'] solves the issue:

import numpy as np
import pandas as pd

def calc_ema(prices, window, smoothing=2):
    ema = [sum(prices.loc[:, 'Price'][:window])/window]
    for price in prices.loc[:, 'Price'][window:]:
        ema.append((price*(smoothing/(1 window))) ema[-1]*(1-(smoothing/(1 window))))
        return ema
   
data = {'Price':[120, 100, 108, 112, 109, 131, 125, 122, 115, 119, 124, 137, 141, 139, 136]}
df=pd.DataFrame(data)

Dema = calc_ema(df,10)
print (Dema)

Output:

[116.1, 117.53636363636363]

CodePudding user response:

You can try passing df['Price'] as an argument instead of df:


    Dema = calc_ema(df['Price'],10)

  • Related