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?
CodePudding user response:
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/
CodePudding user response:
I think the issue is between 'and' and '&'
Give the following a read: https://www.geeksforgeeks.org/difference-between-and-and-in-python/
'and' is the Locigal AND whereas '&' is the bit-and 'AND'
a = 14
b = 4
print(b and a) - 14
print(b & a) - 4
See here too: what is the difference between "&" and "and" in Python?
I would suggest changing you code to use the logical AND
or maybe the following if you do not mind more IF statements
if win == 0:
if loss == 0
winloss.append(0)
elif loss > 0:
winloss.append('All Losses')
elif win > 0:
if loss == 0:
winloss.append('All Wins')
else:
winloss.append(win/loss)
I personally would also find this easier to read as an external user