【问题标题】:Function that determines if a value crosses above another value确定一个值是否超过另一个值的函数
【发布时间】:2018-08-02 15:06:41
【问题描述】:

我正在处理数据框中的一些数据,我发现自己编写的代码包含很多:

def entry_signal(y):
    conditions1 = [np.logical_and(y > 0, y.shift(1) < 0),np.logical_and(y < 0, y.shift(1) > 0)]
    values1 = ['LongEntry','ShortEntry']
    return np.select(conditions1, values1, '')

基本上,如果该值超过 0 并且前一个值小于 0,则它应该为 true。

我尝试创建一个执行此操作的函数,但我不断收到错误:

def cross_above(x,y):
    if np.logical_and(x>y, x.shift(1)<y):
        return True
    else:
        return False

然后我尝试在这里使用它:

def entry_signal(y):
    conditions1 = [cross_above((y,0), y.shift(1) < 0),np.logical_and(y < 0, y.shift(1) > 0)]
    values1 = ['LongEntry','ShortEntry']
    return np.select(conditions1, values1, '')

但我不断得到一个系列的价值真相是模棱两可的。我做错了什么?

【问题讨论】:

标签: python python-3.x pandas function numpy


【解决方案1】:

这是在做这项工作吗?

import numpy as np

def cross_above(x, threshold):
    x = np.asarray(x)
    return np.any( np.logical_and( x[1:]>threshold, x[:-1]<threshold) )

cross_above([1, 2, 3], 1.8) # True
cross_above([3, 2, 1], 1.2) # False
cross_above([3, 2, 1], 0.2) # False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-16
    • 2018-08-11
    • 1970-01-01
    • 2016-09-02
    • 2013-06-01
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    相关资源
    最近更新 更多