Skip to content
Advertisement

Python if statement not working correctly and no idea why

In my code I iterate through dataframes of each year to calculate the number of wins (increase between numbers) and losses (decrease between numbers), and the ratio of wins to losses. The loop I run correctly displays the right number of wins and losses in the dataframe they are eventually pushed to. However, when calculating the win/loss ratio, the if statement isn’t working for no real reason. Here is the loop:

trades = []
wins = []
losses = []
winloss = []
for df in df_years_grouped:
        total_trades = len(df)
        trades.append(total_trades)
        
        win = 0
        loss = 0
        for i, row in df.iterrows():
            if i == 0:
                continue
            elif (df[1][i] > df[1][i-1]):
                win += 1
            elif (df[1][i] < df[1][i-1]):
                loss += 1
        wins.append(win)
        losses.append(loss)
        
        if win == 0 & loss == 0:
            winloss.append(0)
        elif win > 0 & loss == 0:
            winloss.append('All Wins')
        elif win == 0 & loss > 0:
            winloss.append('All Losses')
        else:
            winloss.append(win/loss)

Here is the outcome in the Dataframe:

Trades Win  Lose W/L 
11     5    5    All Wins
42     21   20   All Wins
35     16   18   All Wins
14     9    4    All Wins
23     13   9    All Wins
12     7    4    All Wins
4      2    1    All Wins
4      2    1    All Wins
11     5    5    All Wins
6      3    2    All Wins
0      0    0    0
9      6    2    All Wins
2      0    1    0
16     6    9    All Wins
3      0    2    0
14     7    6    All Wins
206   106   99   1.070707

As you can see it works on one or two but fails on the most, making most of them wins?

Advertisement

Answer

I believe you should be using “and” instead of “&” in the if statements. You can read up on the differences here:

https://www.geeksforgeeks.org/difference-between-and-and-in-python/

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement