Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeError: unsupported operand type(s) for +

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

It gives error:

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

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading