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:
JavaScript
x
29
29
1
trades = []
2
wins = []
3
losses = []
4
winloss = []
5
for df in df_years_grouped:
6
total_trades = len(df)
7
trades.append(total_trades)
8
9
win = 0
10
loss = 0
11
for i, row in df.iterrows():
12
if i == 0:
13
continue
14
elif (df[1][i] > df[1][i-1]):
15
win += 1
16
elif (df[1][i] < df[1][i-1]):
17
loss += 1
18
wins.append(win)
19
losses.append(loss)
20
21
if win == 0 & loss == 0:
22
winloss.append(0)
23
elif win > 0 & loss == 0:
24
winloss.append('All Wins')
25
elif win == 0 & loss > 0:
26
winloss.append('All Losses')
27
else:
28
winloss.append(win/loss)
29
Here is the outcome in the Dataframe:
JavaScript
1
19
19
1
Trades Win Lose W/L
2
11 5 5 All Wins
3
42 21 20 All Wins
4
35 16 18 All Wins
5
14 9 4 All Wins
6
23 13 9 All Wins
7
12 7 4 All Wins
8
4 2 1 All Wins
9
4 2 1 All Wins
10
11 5 5 All Wins
11
6 3 2 All Wins
12
0 0 0 0
13
9 6 2 All Wins
14
2 0 1 0
15
16 6 9 All Wins
16
3 0 2 0
17
14 7 6 All Wins
18
206 106 99 1.070707
19
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/