如何在Pandas数据框的多个列上运行Ta-Lib? [英] How to run Ta-Lib on multiple columns of a Pandas dataframe?
问题描述
我有一个数据框架,其中以几只证券的价格为列,我找不到一次运行TA-Lib的解决方案,因为它需要numpy.ndarray.
I have a data frame with the price of several securities as columns and I can't find a solution to run TA-Lib in one shot because it needs numpy.ndarray.
如何对多个证券运行TA-Lib并获取数据框作为回报?
How can I run TA-Lib over multiple securities and get a data frame in return?
import talib as ta
d = {'security1': [1,2,8,9,8,5], 'security2': [3,8,5,4,3,5]}
df = pd.DataFrame(data=d)
df
Out[518]:
security1 security2
0 1 3
1 2 8
2 8 5
3 9 4
4 8 3
5 5 5
ta.EMA(df, 2)
TypeError: Argument 'real' has incorrect type (expected numpy.ndarray, got DataFrame)
ta.EMA(df['security1'], 2)
Out[520]:
0 NaN
1 1.500000
2 5.833333
3 7.944444
4 7.981481
5 5.993827
dtype: float64
type(df['security1'])
Out[524]: pandas.core.series.Series
当我将数据帧转换为numpy.ndarray时,它仍然引发异常:
When I convert the data frame to a numpy.ndarray it still throws an exception:
ta.EMA(df.values, 2)
Out[528]: Exception: input array type is not double
谢谢.
推荐答案
TA-Lib需要浮点数据,而您的数据是不可或缺的.
TA-Lib is expecting floating point data, whereas yours is integral.
这样,在构造数据框时,您需要通过指定dtype=numpy.float64
来强制输入数据:
As such, when constructing your dataframe you need to coerce the input data by specifying dtype=numpy.float64
:
import pandas
import numpy
import talib
d = {'security1': [1,2,8,9,8,5], 'security2': [3,8,5,4,3,5]}
df = pandas.DataFrame(data=d, dtype=numpy.float64) # note numpy.float64 here
TA-Lib需要一维数组,这意味着它可以在pandas.Series
上运行,但不能在pandas.DataFrame
上运行.
TA-Lib expects 1D arrays, which means it can operate on pandas.Series
but not pandas.DataFrame
.
但是,您可以使用 pandas.DataFrame.apply
将功能应用于数据框的每一列
You can, however, use pandas.DataFrame.apply
to apply a function on each column of your dataframe
df.apply(lambda c: talib.EMA(c, 2))
security1 security2
0 NaN NaN
1 1.500000 5.500000
2 5.833333 5.166667
3 7.944444 4.388889
4 7.981481 3.462963
5 5.993827 4.487654
这篇关于如何在Pandas数据框的多个列上运行Ta-Lib?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!