Reputation: 381
I have a df as such:
Week_Number Year Open Close mean_return labels
0 0 2020 46.270000 46.045000 -0.59950 red
1 1 2020 46.748001 47.506000 1.57500 green
2 2 2020 50.888000 51.382000 1.21760 green
3 3 2020 52.724999 52.530000 -0.20475 red
4 4 2020 49.892001 49.424001 -2.10100 red
... ... ... ... ... ... ...
100 48 2021 123.186000 120.751999 -1.44040 red
101 49 2021 119.786000 119.144000 0.10760 green
102 50 2021 111.006000 108.998000 -1.43240 red
103 51 2021 107.752499 108.429998 0.98400 green
104 52 2021 110.777500 110.529999 -0.05050 red
and I'm trying to calculate how much profit/loss I would make at the end of the 52 weeks according to the labels ('red', 'green').
This is my code so far...
stock = 100 / num
col = 'green'
for n in new_df[2:].itertuples():
if n[-1] == 'green' and col == 'green':
col = 'green'
if n[-1] == 'green' and col == 'red':
stock = stock * n[3]
col = 'red'
if n[-1] == 'red' and col == 'red':
col = 'red'
if n[-1] == 'red' and col == 'green':
stock = stock / n[4]
trading_strategy = stock * new_df.iloc[-2].values[3]
trading_strategy
Essentially what it's saying is, if the week before is 'red' and this week is 'green' then buy, if it is 'green' before and 'red' now sell...
I had run the same script previously and ended up with a value ~ 300 , but now I'm getting 3.132446251028895e-85 and I have absolutely no idea why.
I've been at it for a few hours now and it's 2am, maybe there's something glaringly obvious that I'm not seeing at the moment - any help?
Upvotes: 0
Views: 52
Reputation: 1439
You can group by year and compute the sum of returns
df[["Year", "mean_return"]].groupby("Year").sum()
Upvotes: 2