TA-Lib / ta-lib-python

Python wrapper for TA-Lib (http://ta-lib.org/).
http://ta-lib.github.io/ta-lib-python
Other
9.69k stars 1.76k forks source link

How to Calculate Stocastic RSI using Talib on Multi-Index Dataframe? #293

Open baqarjafri opened 4 years ago

baqarjafri commented 4 years ago

I have been trying to calculate Stocastic RSI on multi-index dataframe by using "groupby" symbol, and then calling inline function. Following is the code:

df['fastk'],df['fastd'] = df.groupby('Symbol')['Close'].apply(lambda y: talib.STOCHRSI(y, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0))

The error is:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\jafre\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\frame.py", line 2519, in __setitem__
    self._set_item(key, value)
  File "C:\Users\jafre\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\frame.py", line 2585, in _set_item
    value = self._sanitize_column(key, value)
  File "C:\Users\jafre\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\frame.py", line 2760, in _sanitize_column
    value = _sanitize_index(value, self.index, copy=False)
  File "C:\Users\jafre\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\series.py", line 3121, in _sanitize_index
    raise ValueError('Length of values does not match length of ' 'index')
ValueError: Length of values does not match length of index

Can someone help with the changes in the code so that multiple output columns can be created in this multi-index dataframe?

Pk13055 commented 4 years ago

Try running a list comprehension along the group and then recombining the results into the relevant rows