Reputation: 59
I'm very new to pandas and I'm trying to convert daily stock return into weekly stock returns by finding the product of (1 + return) for each day Monday to Friday.
Here is an example of what i have so far (data is just an example, not real numbers):
In[1]: df
In [2]:
Date AAPL NFLX INTC
2019-09-09 0.01 0.0012 0.00873
2019-09-10 0.014 0.0074 0.0837738
2019-09-11 0.0123 0.007123 0.09383
2019-09-12 0.0028 0.07234 0.0484
2019-09-13 0.00172 0.8427 0.09484
My dataset is much larger than what I'm showing. But essentially I just want to find the product of (1+return) for every consecutive Monday to Friday.
The ideal output would be a dataframe with fridays as indices, and then weekly return values displayed under the stock tickers
Upvotes: 0
Views: 1571
Reputation: 221
The line of code below should do it:
(1+df).resample('W-FRI').prod()-1
What the line above is doing is resampling the (1 + daily return) (check pandas resample documentation for further information) to a weekly frequency with Friday set as the resampling day ('W-FRI'). Finally, the prod() is multiplying the (1 + daily return) when weekly resampling is perfomed to return the accumulated return for each week.
Upvotes: 2