gpt4 book ai didi

python - 根据名称作为列表中的字符串调用函数

转载 作者:太空宇宙 更新时间:2023-11-03 13:16:59 25 4
gpt4 key购买 nike

Terms: 
talib: Technical Analysis Library (stock market indicators, charts etc)
CDL: Candle or Candlestick

简短版本:我想根据字符串 'some_function' 运行 my_lib.some_function()

在 quantopian.com 上,为了简洁起见,我想在一个循环中调用以 CDL 开头的所有 60 个 talib 函数,例如 talib.CDL2CROWS()。首先将函数名称提取为字符串,然后通过与字符串匹配的名称运行函数。

这些 CDL 函数都采用相同的输入,即一段时间内的开盘价、最高价、最低价和收盘价列表,此处的测试仅使用长度为 1 的列表来简化。

import talib, re
import numpy as np

# Make a list of talib's function names that start with 'CDL'
cdls = re.findall('(CDL\w*)', ' '.join(dir(talib)))
# cdls[:3], the first three like ['CDL2CROWS', 'CDL3BLACKCROWS', 'CDL3INSIDE']

for cdl in cdls:
codeobj = compile(cdl + '(np.array([3]),np.array([4]),np.array([5]),np.array([6]))', 'talib', 'exec')
exec(codeobj)
break
# Output: NameError: name 'CDL2CROWS' is not defined

尝试第二个:

import talib, re
import numpy as np

cdls = re.findall('(CDL\w*)', ' '.join(dir(talib)))

for cdl in cdls:
codeobj = compile('talib.' + cdl + '(np.array([3]),np.array([4]),np.array([5]),np.array([6]))', '', 'exec')
exec(codeobj)
break
# Output: AssertionError: open is not double

我没有在网上找到那个错误。

相关,我问那边的问题:https://www.quantopian.com/posts/talib-indicators (111 浏览量,暂无回复)

对于任何对烛台感兴趣的人:http://thepatternsite.com/TwoCrows.html


更新

这很有效,在 Anzel 的聊天帮助下,列表中的 float 可能是关键。

import talib, re
import numpy as np
cdls = re.findall('(CDL\w*)', ' '.join(dir(talib)))
# O, H, L, C = Open, High, Low, Close
O = [ 167.07, 170.8, 178.9, 184.48, 179.1401, 183.56, 186.7, 187.52, 189.0, 193.96 ]
H = [ 167.45, 180.47, 185.83, 185.48, 184.96, 186.3, 189.68, 191.28, 194.5, 194.23 ]
L = [ 164.2, 169.08, 178.56, 177.11, 177.65, 180.5, 185.611, 186.43, 188.0, 188.37 ]
C = [ 166.26, 177.8701, 183.4, 181.039, 182.43, 185.3, 188.61, 190.86, 193.39, 192.99 ]
for cdl in cdls: # the string that becomes the function name
toExec = getattr(talib, cdl)
out = toExec(np.array(O), np.array(H), np.array(L), np.array(C))
print str(out) + ' ' + cdl

关于如何向字符串转换函数添加参数的选择:

toExec = getattr(talib, cdl)(args)
toExec()

toExec = getattr(talib, cdl)
toExec(args)

最佳答案

更简单的方法是使用抽象库

import talib

# All the CDL functions are under the Pattern Recognition group
for cdl in talib.get_function_groups()['Pattern Recognition']:
# get the function object
cdl_func = talib.abstract.Function(cdl)

# you can use the info property to get the name of the pattern
print('Checking', cdl_func.info['display_name'], 'pattern')

# run the function as usual
cdl_func(np.array(O), np.array(H), np.array(L), np.array(C))

关于python - 根据名称作为列表中的字符串调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26421734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com