Below is an extract of a dataframe containing stock information with multiple tickers:
ticker date open high low close volume rsi
0 A2M 2015-03-31 0.555 0.595 0.530 0.565 4816294.0 NaN
1 A2M 2015-04-30 0.475 0.500 0.475 0.500 531816.0 NaN
2 A2M 2015-05-29 0.475 0.475 0.455 0.465 5665854.0 NaN
3 A2M 2015-06-30 0.640 0.650 0.630 0.640 1691918.0 63.636364
4 A2M 2015-07-31 0.750 0.760 0.730 0.735 714927.0 76.047904
64672 ZFX 2008-01-31 10.090 10.490 9.860 10.280 4484500.0 NaN
64673 ZFX 2008-02-29 10.650 11.130 10.650 11.130 15525073.0 NaN
64674 ZFX 2008-03-31 10.010 10.080 9.920 9.980 4256951.0 NaN
64675 ZFX 2008-04-30 9.900 10.190 9.850 10.100 3522569.0 21.238157
64676 ZFX 2008-05-30 9.750 9.750 9.450 9.500 8270995.0 16.253845
I require the addition of indicators from the ta-lib
package, with the indicators to be grouped by ticker
. I successfully implemented the RSI using the following code:
monthly_raw_data['rsi'] = monthly_raw_data.groupby('ticker')['close'].apply(lambda x: ta.RSI(x, timeperiod=3))
However, when trying to implement CCI, it has multiple arguments and I don't know how to implement through a lambda expression. I've tried the below:
monthly_raw_data['cci'] = monthly_raw_data.groupby('ticker')['close'].apply(lambda x: ta.CCI(monthly_raw_data['high'], monthly_raw_data['low'], x, timeperiod=12))
I get the following error message:
Exception: input array lengths are different
I have also tried separating into a different function:
def cci(df):
cci = ta.CCI(monthly_raw_data['high'], monthly_raw_data['low'], monthly_raw_data['close'], timeperiod=6)
return cci
monthly_raw_data['cci'] = monthly_raw_data.groupby('ticker').apply(lambda df: cci(df))
However, I receive the following error message:
TypeError: incompatible index of inserted column with frame index
When I create a separate dataframe to see what is happening it seems to be changing the dataframe to the below:
0 1 2 3 4 5 6 7 8 9 ... 64667 64668 64669 64670 64671 64672 64673 64674 64675 64676
ticker
A2M NaN NaN NaN NaN NaN 41.584158 28.0 82.316119 199.492386 172.390572 ... -39.470637 -0.791007 -90.955414 -147.191601 -130.347794 -124.040219 -72.940833 -79.655329 -62.732749 -83.135392
AAN NaN NaN NaN NaN NaN 41.584158 28.0 82.316119 199.492386 172.390572 ... -39.470637 -0.791007 -90.955414 -147.191601 -130.347794 -124.040219 -72.940833 -79.655329 -62.732749 -83.135392
AAP NaN NaN NaN NaN NaN 41.584158 28.0 82.316119 199.492386 172.390572 ... -39.470637 -0.791007 -90.955414 -147.191601 -130.347794 -124.040219 -72.940833 -79.655329 -62.732749 -83.135392
ABB NaN NaN NaN NaN NaN 41.584158 28.0 82.316119 199.492386 172.390572 ... -39.470637 -0.791007 -90.955414 -147.191601 -130.347794 -124.040219 -72.940833 -79.655329 -62.732749 -83.135392
ABC NaN NaN NaN NaN NaN 41.584158 28.0 82.316119 199.492386 172.390572 ... -39.470637 -0.791007 -90.955414 -147.191601 -130.347794 -124.040219 -72.940833 -79.655329 -62.732749 -83.1353
Any help would be greatly appreciated.