将派生率的Pine脚本转换为Python等效

时间:2019-11-12 16:16:48

标签: python pandas pine-script

我有一部分要在基于python的计算中使用的pine脚本。我的目标是提高效率。如果我可以在不迭代Pandas数据帧的情况下进行计算,那就太好了。

这是源脚本:

//@version=3
// Copyright (c) 2018-present, Alex Orekhov (everget)
// Volatility Ratio script may be freely distributed under the MIT license.

_highest(length, start) =>
    out = nz(high[start])
    for i = start + 1 to length - 1
        prev = nz(high[i])
        out := out < prev ? prev : out
    out

_lowest(length, start) =>
    out = nz(low[start])
    for i = start + 1 to length - 1
        prev = nz(low[i])
        out := out > prev ? prev : out
    out

max = max(_highest(length, 1), close[length + 1])
min = min(_lowest(length, 1), close[length + 1])

vr = tr(true) / (max - min)

我的代码如下。烛台代表带有DateTimeIndex的数据帧,每行代表带有其他列的普通OHLC数据: enter image description here

    for row in candlesticks.itertuples():
        current_index = candlesticks.index.get_loc(row.Index)
        if current_index >= 1:
            previous_close = candlesticks.iloc[current_index - 1, candlesticks.columns.get_loc('close')]
            candlesticks.iloc[current_index, candlesticks.columns.get_loc('ttr')] = max(
                row.high - row.low,
                abs(row.high - previous_close),
                abs(row.low - previous_close))

        if current_index > 14:
            candlesticks.iloc[current_index, candlesticks.columns.get_loc('vr_14')] = candlesticks.iloc[current_index, candlesticks.columns.get_loc('ttr')] / (
                max(candlesticks.high[current_index - 13: current_index].max(), candlesticks.close[current_index - 15]) - min(
                candlesticks.low[current_index - 13: current_index].min(), candlesticks.close[current_index - 15]))
        if current_index > 10:
            candlesticks.iloc[current_index, candlesticks.columns.get_loc('vr_10')] = candlesticks.iloc[current_index, candlesticks.columns.get_loc('ttr')] / (
                max(candlesticks.high[current_index - 9: current_index].max(), candlesticks.close[current_index - 11]) - min(
                candlesticks.low[current_index - 9: current_index].min(), candlesticks.close[current_index - 11]))
        if current_index > 7:
            candlesticks.iloc[current_index, candlesticks.columns.get_loc('vr_7')] = candlesticks.iloc[current_index, candlesticks.columns.get_loc('ttr')] / (
                max(candlesticks.high[current_index - 6: current_index].max(), candlesticks.close[current_index - 8]) - min(
                candlesticks.low[current_index - 6: current_index].min(), candlesticks.close[current_index - 8]))

它有效,只是非常慢。

0 个答案:

没有答案