coinmaster
coinmaster

Reputation: 143

TypeError: ufunc 'bitwise_and' not supported for the input types

I'm trying to write some code that will allow me quickly determine whether a variable is higher, lower, or equal to another variable within a dataframe at each index point.

As shown here:

import numpy as np
import datetime
import pandas as pd
import operator

previous_cross = 'both'

ops = {
    '+' : operator.add,
    '-' : operator.sub,
    '*' : operator.mul,
    '/' : operator.truediv,  # use operator.div for Python 2
    '%' : operator.mod,
    '^' : operator.xor,
    '<' : operator.lt,
    '<=' : operator.le,
    '==' : operator.eq,
    '!=' : operator.ne,
    '>=' : operator.ge,
    '>' : operator.gt
} 

#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

df = pd.read_csv(r'C:\EURUSD_mt5_ticks.csv', parse_dates=['Date'])
df.columns = ['Date', 'Ask_Price', 'Ask_Volume', 'Bid_Price', 'Bid_Volume', 'Spread']
df['Date'] = pd.to_datetime(df['Date'].astype('datetime64[ns]'), exact=True, cache=True, format='%Y-%m-%d  %H:%M:%S.%f')  
MA1 = df['Ask_Price'].rolling(4).mean()
MA2 = df['Ask_Price'].rolling(21).mean()
df['MA1'] = MA1
df['MA2'] = MA2

#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def tbar_number(n):
        return tbar_count - n

    
def vcross(variable1_column, direction, variable2_column, vdataframe, width):

    global previous_cross


    
    #number of bars previous from the current bar, 
    width_value = tbar_number(width)
    
    for i in range(width_value+1):

        width_value_count = i
  
        #data from the index of each bar within the 'width' bar range
        v1_width_data = df.loc[width_value_count, variable1_column] 
        v2_width_data = df.loc[width_value_count, variable2_column]
                                    
            #if variable 1 crosses above or is equal to(depending on chosen symbol) variable 2, return true
        if (direction == '>' or '>=') & (ops[direction](v1_width_data, v2_width_data)) & (previous_cross == 'short' or 'both'):
            if (direction == '>=') and (v1_width_data == v2_width_data):
                return True
            if direction == '>':
                previous_cross = 'long'  
                return True
        
             #if variable 1 crosses below or is equal to(depending on chosen symbol) variable 2, return true
        elif (direction == '<' or '<=') & (ops[direction](variable1, variable2)) & (previous_cross == 'long' or 'both'):
            if (direction == "<=") and (v1_width_data == v2_width_data): 
                return True
            if direction == '<':
                previous_cross = 'short'
                return True

             #if variable 1 is equal to(depending on chosen symbol) variable 2, return true
        elif (direction == '==') & (ops[direction](variable1, variable2)):
            return True
        
        else:
            return False
        
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
for tbar_count in range(len(df)): 
    
  if vcross('MA1', '>', 'MA2', df, 1):
  print("hi")

Dataframe data


Date    Ask_Price   Ask_Volume  Bid_Price   Bid_Volume  Spread  MA1 MA2
0   2021-08-11 00:00:00.686 1.17199 0.75    1.17195 0.75    0.00004 NaN NaN
1   2021-08-11 00:00:00.989 1.17201 2.43    1.17195 3.37    0.00006 NaN NaN
2   2021-08-11 00:00:05.004 1.17198 0.75    1.17196 4.87    0.00002 NaN NaN
3   2021-08-11 00:00:05.203 1.17200 0.75    1.17197 0.10    0.00003 1.171995    NaN
4   2021-08-11 00:00:10.654 1.17201 0.75    1.17198 0.10    0.00003 1.172000    NaN

But I get this error

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-f2dbb6db13b8> in <module>
     80 for tbar_count in range(len(df)):
     81 
---> 82     if vcross('MA1', '>', 'MA2', df, 1):
     83         print("hi")
     84 

<ipython-input-7-f2dbb6db13b8> in vcross(variable1_column, direction, variable2_column, vdataframe, width)
     55 
     56             #if variable 1 crosses above or is equal to(depending on chosen symbol) variable 2, return true
---> 57         if (direction == '>' or '>=') & (ops[direction](v1_width_data, v2_width_data)) & (previous_cross == 'short' or 'both'):
     58             if (direction == '>=') and (v1_width_data == v2_width_data):
     59                 return True

TypeError: ufunc 'bitwise_and' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

I haven't been able to find the solution through google. Most of the time the issue seems to be related to not encapsulating the conditions when using & but I have encapsulated everything already.

Can anyone lend me a hand?

Upvotes: 0

Views: 817

Answers (1)

hpaulj
hpaulj

Reputation: 231475

Careful with the use of or in your tests. For example:

In [351]: direction='++'; direction=='>' or '>='
Out[351]: '>='
In [352]: direction='>'; direction=='>' or '>='
Out[352]: True

This does a direction=='>'; if that is True, it returns True; if False, it returns the value after the or. It is not the same as

In [354]: direction='++';(direction=='>') or (direction=='>=')
Out[354]: False
In [355]: direction='>';(direction=='>') or (direction=='>=')
Out[355]: True
In [356]: direction='>=';(direction=='>') or (direction=='>=')
Out[356]: True

and equivalent test is

direction in ['>','>=']

Upvotes: 1

Related Questions