I am new to python pandas and trying to get the rate of return with pct_change (). I would like to get the monthly rate of change in the feed code. This is my current code:
In [134]:
df3 = pd.read_csv(r'C:\Users\sector_set.csv')
df3.set_index('Date', inplace= True)
df3= pd.DataFrame(df3,columns = ['Feed','Close'])
grouped = df3.groupby('Feed')
df3 = grouped.resample('BM', how=lambda x:x[-1])
df3['Rate_Return'] = df3.pct_change()
df3
OUTPUT:
Close Rate_Return
Feed Date
A 2015-09-30 5.60 NaN
2015-10-30 5.75 0.026786
AAV 2015-09-30 4.32 -0.248696
2015-10-30 4.62 0.069444
I have two problems:
The calculated rate of return is incorrect because it refers to the price of the previous day to calculate the return for the next feed code. For example, Feed AAV 2015-09-30 should be NaN, not -0.248696
I would like to delete all NaN
I am trying to calculate the return values in order to get something like this:
Output:
Close Rate_Return
Feed Date
A 2015-10-30 5.75 0.026786
AAV 2015-10-30 4.32 0.069444
What is the best way to do this? Thanks in advance for any help
Dusty source
share