1

I'm working with some data in a dataframe and I find myself writing code that includes this a lot:

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, '')

Essentially if the value crosses above 0 and the previous value is less than 0 than it should be true.

I tried to create a function that did this but I keep getting an error:

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

I then tried to use it here:

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, '')

But I keep getting an truth of value of a series is ambiguous. What am i doing wrong?

Laurent H.
  • 6,316
  • 1
  • 18
  • 40
novawaly
  • 1,051
  • 3
  • 12
  • 27

1 Answers1

1

Is this doing the job?

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
xdze2
  • 3,986
  • 2
  • 12
  • 29