I have a dataframe with stock data sorted by name and date. I'm trying to apply the KAMA (Kaufman Adaptive Moving Average) function to each stock. The function works with the df when I apply it to a new column but not with groupby.
Below is some dummy data and with what I've tried so far in Jupyter. It returns: TypeError: 'Series' objects are mutable, thus they cannot be hashed
import numpy as np
import pandas as pd
import talib as tb
df = pd.DataFrame()
df['NAME'] = ['A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A',
'A','B','B','B','B','B','B','B','B','B','B','B','B','B','B','B','B','B','B',
'B','B']
df['CLOSE'] = np.random.randint(1,100,df.shape[0])
df['NameNumber']=df.groupby('NAME').cumcount()
cols = ['NAME', 'NameNumber']
df['CN_PK'] = df[cols].apply(lambda row: '_'.join(row.values.astype(str)), axis=1)
close = df['CLOSE']
df['KAMA'] = tb.KAMA(close, timeperiod = 3)
df['GrpKAMA'] = df.groupby('NAME')['CLOSE'].apply(tb.KAMA(close,timeperiod = 3))
df.head(50)
To do this, you need to provide data by group:
df['GrpKAMA'] = df.groupby('NAME')['CLOSE'].apply(lambda x: tb.KAMA(x,timeperiod = 3))
or for example calling a custom function (you can print data in it and see what it contains):
def f(x):
return tb.KAMA(x,timeperiod = 3)
df['GrpKAMA'] = df.groupby('NAME')['CLOSE'].apply(f)