通达信 SMA函数与ta-lib中的SMA的区别——julia实

2020-08-10  本文已影响0人  昵称违法

最近发现talib里面的 SMA和通达信里面的SMA的计算方法是不一样的。
经过查看资料,梳理他们的区别如下
talib里的SMA相当于mean

而通达信里面的SMA计算如下:

通达信版本的SMA函数

【SMA】:求移动平均
用法:SMA(X,N,M),求X的N日移动平均,M为权重。
算法:若Y=SMA(X,N,M),则 Y=[M*X+(N-M)*Y']/N,其中Y'表示上一周期Y值,N必须大于M。
例如:SMA(CLOSE,30,1) 表示求30日移动平均价。

-------------------
SMA易懂
SMA3速度快
-------------------

备注:ta-lib中的移动窗口求和函数,比我自编的函数要快200多倍,我优化julia的代码后,ta-lib仍然比我自编的函数快28倍,究其原因:ta-lib底层用c完成,他们优化的好,肯定用多线程(具体没看源码,待确认)。

function SMA(ary::Array{Float64,1},n::Int64,m::Int64)
    rtn_ary::Array{Float64,1} = Array{Float64,1}(undef,length(ary))   
    for (i,c) in zip(1:length(ary),ary)
        if i == 1
            rtn_ary[i] = c * m / n           
        else
            rtn_ary[i] = (c * m + (n-m) * rtn_ary[i-1]) / n             
        end      
    end
    return rtn_ary
end

function SMA2(X,N,M)
    Y = 0
    res = []
    for x in X
        Y = (M * x + (N-M) * Y) / N
        push!(res,Y)
    end
    res
end

function SMA3(X::Array{Float64,1},N::Int64,M::Int64)
    Y::Float64 = 0.0
    res = Array{Float64,1}(undef,length(X))
    for (i,x) in zip(1:length(X),X)
        Y = (M * x + (N-M) * Y) / N
        res[i] = Y
    end
    res
end

function SMA4(X,N,M)
    Y = 0
    res = begin
        X .|> x-> begin
            Y = (M * x + (N-M) * Y) / N          
        end        
    end   
end
ary = [float(x) for x in 1:50000000]
n = 20
m = 3
@time SMA(ary,n,m)
0.448360 seconds (2 allocations: 381.470 MiB, 1.55% gc time)
@time SMA2(ary,n,m)
8.112229 seconds (50.00 M allocations: 1.155 GiB, 74.59% gc time)
@time SMA3(ary,n,m)
0.326152 seconds (2 allocations: 381.470 MiB)
@time SMA4(ary,n,m)
6.316757 seconds (250.00 M allocations: 4.098 GiB, 23.23% gc time)
上一篇下一篇

猜你喜欢

热点阅读