1

Do you know how I can simplify this logical expression? I am trying to fix it for hours, but I can't.

if (trade_dur == 0 and ( ( is_short # Red candle (for longs) and row[OPEN_IDX] < row[CLOSE_IDX] # Red candle and trade.open_rate > row[OPEN_IDX] # trade-open above open_rate and close_rate < row[CLOSE_IDX] # closes below close ) or ( not is_short # green candle (for shorts) and row[OPEN_IDX] > row[CLOSE_IDX] # green candle and trade.open_rate < row[OPEN_IDX] # trade-open below open_rate and close_rate > row[CLOSE_IDX] # closes above close ) )): 
4
  • Does it matter what happens in the cases where row[OPEN_IDX] == row[CLOSE_IDX], trade.open_rate == row[OPEN_IDX], and/or close_rate == row[CLOSE_IDX]? Commented Jul 4, 2022 at 7:04
  • Yes, because it's a backtesting script for an open-source trading bot, using this logical expression algorithm can understand whether portofolio went up or down. Open and close numbers can't be the same you see. Commented Jul 4, 2022 at 7:12
  • whenever I have a large expression that could be simplified, I apply the rules of boolean algebra to the expression and minimize it that way. This is not necessarily a huge expression but you can still minimize it using boolean algebra. Commented Jul 4, 2022 at 7:47
  • I went through several online boolean algebra simplifier and none of them could find a better form for (A * B * C * D)+(~A*~B*~C*~D). I would still do something similar to what @Ni2Be proposed to make the whole thing more readable. Commented Jul 4, 2022 at 8:52

1 Answer 1

1

If you are in a function, you could use an early return like:

if(trade_dur != 0): return 

You could then define some bools with appropriate names to make it more readable:

 is_red = row[OPEN_IDX] < row[CLOSE_IDX] trade_open_above = trade.open_rate > row[OPEN_IDX] closes_below = trade.open_rate > row[OPEN_IDX] : is_tradable = (is_short and is_red and trade_open_above and closes_below) or (not is_short and is_green and trade_open_below and closes_above ) if(is_tradable) : ... 
Sign up to request clarification or add additional context in comments.

1 Comment

it looks all the booleans on the first halve are just negated on the second so I would personally prefer (is_short and is_red and trade_open_above and closes_below) or (not is_short and not is_red and not trade_open_above and not trade closes_below) but I admit it's largely a matter of taste.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.