使用VBA的Lee-Ready蜱测试

时间:2016-03-22 13:23:17

标签: excel vba excel-vba

我正在尝试建立Lee-Ready蜱测试,以便使用Excel从蜱数据估算交易方向。我有一个包含交易价格降序的数据集,我正在尝试构建一个能够以尽可能有效的方式遍历所有4m +单元的VBA代码。

估计贸易指标的规则如下:

If Pt>Pt-1, then d=1
If Pt<Pt-1, then d=-1
If Pt=Pt-1, then d is the last value taken by d.

所以举一个具体的例子,我想改变这个:

P1;P2;P3;P4
1.01;2.02;3.03;4.04
1.00;2.03;3.03;4.02
1.01;2.02;3.01;4.04
1.00;2.03;3.00;4.04

进入这个

d1;d2;d3;d4
1;-1;1;1
-1;1;1;-1
1;-1;1;0
0;0;0;0

1 个答案:

答案 0 :(得分:0)

相当简单的嵌套循环就足够了:

Function LeeReady(Prices As Variant) As Variant
    'Given a range or 1-based, 2-dimensional variant array
    'Returns an array of same size
    'consisiting of an array of the same size
    'of trade directions computed according to
    'Lee-Ready rule

    Dim i As Long, j As Long
    Dim m As Long, n As Long
    Dim priceData As Variant, directions As Variant
    Dim current As Variant, previous As Variant

    If TypeName(Prices) = "Range" Then
        priceData = Prices.Value
    Else
        priceData = Prices
    End If

    m = UBound(priceData, 1)
    n = UBound(priceData, 2)
    ReDim directions(1 To m, 1 To n) As Long 'implicitly fills in bottom row with 0s

    For i = m - 1 To 1 Step -1
        For j = 1 To n
            current = priceData(i, j)
            previous = priceData(i + 1, j)
            If current > previous Then
                directions(i, j) = 1
            ElseIf current < previous And previous > 0 Then
                directions(i, j) = -1
            Else
                directions(i, j) = directions(i + 1, j)
            End If
        Next j
    Next i

    LeeReady = directions

End Function

这可以从子系统调用或直接在工作表上使用:

enter image description here

在这里,我只突出显示了一个正确大小的单元格块来保存输出,然后使用公式=LeeReady(A2:D5)(按Ctrl+Shift+Enter接受它作为数组公式)。

On Edit:我稍微修改了代码(通过将And previous > 0子句添加到主循环中的If语句),以便它现在可以处理列中有更多行的范围比其他专栏。该代码假定价格数据始终> 0并填充返回数组,其中0s作为占位符,列在比其他列更早的列中:

enter image description here