I have a DataFrame as below
I want to get the standard deviation of stock returns st.dev (T1/T0-1,T2/T1-1..etc)
for example, st.dev((9.5/36.5)-1,(6.125/9.5)-1...etc)
The result will be added to DataFrame number 2.
Can u please suggest the best way to do it? Obviously, I need to do it to every stock. Can you please help?
Thanks in Advance!
P.S: you can ignore the standard deviation part, if you can just help me with the returns, I will do the rest.
You can get the T1/T0-1
values with df.pct_change. From there you can use .agg
to aggregate with several functions.
# sample df
# please always provide a sample that can be easily pasted and tested
# you could get it with `df.head(10).to_dict('split')`
df = pd.DataFrame({
'AAPL': [36.5, 9.5, 6.125, 40.25, 43.875, 40, 42.25],
'TSL': [44, 43.625, 47.875, 64.25, 17.375, 14.124, 44.75],
'GDXJ': [43.875, 13.625, 22.5, 37.125, 5.5, 21.125, 21.25],
'DAL': [11.625, 33.25, 4.625, 36, 36.25, 14.875, 31.75]
})
df2 = df.pct_change().agg(['mean', 'std']).T
Output
mean std
AAPL 0.755739 2.379347
TSL 0.280437 0.992349
GDXJ 0.434482 1.340593
DAL 1.389140 2.838230