有些指标用talib实现不太了。
指标含义大概是这样的,回溯过去几根bar,如果依次走高是上升,返回0,否则 返回1
主要问题是,我需要对返回的结果 进行回溯,不一定是使用最新(最后一个)的结果。
mc代码,接近自然语言,应该比较好理角,供参考
inputs:
InputData( numericseries ),
BarCount( numericsimple ),
NotStrict( truefalse );
vars:
result( 0 ), PrevValue(0), CurrValue(0), Index(0);
PrevValue = InputData[BarCount-1];
result = 0;
For Index = 1 to BarCount-1 begin
CurrValue = InputData[BarCount - 1 - Index];
If (CurrValue < PrevValue) then begin
// indicator is falling, not rising
result = 0;
break;
end;
if(NotStrict = false and CurrValue = PrevValue) then begin
result = 0;
break;
end;
if(CurrValue > PrevValue) then begin
result = 1;
end;
PrevValue = CurrValue;
end;
rising = result;
我尝试的python代码
def IsRisingFunc(self, arrayvalue, barcount: int, NotStrict: bool=True,
array: bool = False
) -> Union[int, np.ndarray]:
""""
判断是上涨趋势,回溯barcount个价格序列,从左向右循环比较,均大为上升
"""
PreValue = arrayvalue[-barcount]
result = []
for num in range(-(barcount-1),0):
CurrValue = arrayvalue[num]
if CurrValue < PreValue:
result.append(0)
break
if NotStrict == False and CurrValue == PreValue:
result.append(0)
break
if CurrValue > PreValue:
result.append(1)
PreValue = CurrValue
resultarray = np.array(result)
if array:
return resultarray
return resultarray[-1]
修改了一下,应该是可以运行了,之前的错误是均线指标调用时,返回序列,直接当数值来比较了,加个[-1]就好了。
现在能回测,但就是返回一个错误提示
File "D:\Tmp\vnpy\strategies\ma_bo_v1.py", line 111, in on_Xmin_bar
array =False
File "d:\vnstudio\lib\site-packages\vnpy\app\xtool\XQuantTool.py", line 219, in SQ_IsRising
return resultarray[-1]
IndexError: index -1 is out of bounds for axis 0 with size 0
在策略文件是这样写的
self.ma_fast = am.sma(self.ma_f_len, array=True)
self.ma_slow = am.sma(self.ma_s_len, array=False)
self.IsRising = am.SQ_IsRising(self.ma_fast,5,NotStrict=True,
array =False
)
# longcond = self.ma_fast > self.ma_slow
longcond = self.IsRising == 1 and self.ma_fast[-1] > self.ma_slow
shortcond = self.ma_fast[-1] < self.ma_slow
...
尝试看ta_lib的源码,看看有没有启示,但C实在太难了。
因为经常使用其他指标值 作为参数输入,所以最后还是方法化了他。
请大家帮帮忙,如果把这个改写到符合vnpy, arraymanager的要求。
谢谢!