python-3.x 如果当前项产生错误,如何从下一个循环项继续循环?

k5ifujac  于 2022-12-15  发布在  Python
关注(0)|答案(1)|浏览(125)

我有一个函数,可以从Pandas数据存储器中的OHLC值计算RSI指标。该函数如下:

def rsi_indicator(df):
    diff = df.close.diff().values
    gains = diff
    losses = -diff
    with np.errstate(invalid='ignore'):
        gains[(gains < 0) | np.isnan(gains)] = 0.0
        losses[(losses <= 0) | np.isnan(losses)] = 1e-10  # we don't want divide by zero/NaN
    n = 14
    m = (n - 1) / n
    ni = 1 / n
    try:
        g = gains[n] = np.nanmean(gains[:n])
        l = losses[n] = np.nanmean(losses[:n])
    except IndexError as e:
         ????
    gains[:n] = losses[:n] = np.nan
    for i, v in enumerate(gains[n:], n):
        g = gains[i] = ni * v + m * g
    for i, v in enumerate(losses[n:], n):
        l = losses[i] = ni * v + m * l
    rs = gains / losses
    rsi = 100 - (100 / (1 + rs))
    return rsi

我循环通过几个 Dataframe 来计算RSI,但每当我有一个 Dataframe 没有足够的记录来计算指标值时,我就会得到一个IndexError:

IndexError: index 14 is out of bounds for axis 0 with size 13

当我遇到这样的错误时,我如何继续使用循环列表中的下一项?
我添加了一些????在我需要的代码来修复这个问题,否则随时更改代码,无论你喜欢。

gopyfrb3

gopyfrb31#

一般来说,不处理错误或异常而将其隐藏是一种不好的做法,但可以像这样轻松地做到这一点:

# block raising an exception
except:
    pass # doing nothing on exception```
This can obviously be used in any other control statement, such as a loop:

for i in xrange(0,960):
    try:
        ... run your code
    except:
        pass

相关问题