returns is a python data frame and this is the head. this is just for 2 stocks daily returns
date NOW BBY
2013-09-30 NaN NaN
2013-10-01 -0.008855 0.012000
2013-10-02 0.015149 -0.007642
2013-10-03 -0.002296 0.000796
2013-10-04 0.043720 0.012206
I have a simple code that calculates annualized sharpe ratio for stocks
Function
N= 252
sharpe = np.sqrt(N)* returns.mean()/returns.std()
print (sharpe)
and this is the output when i print(sharpe)
NOW 0.906136
BBY 0.667774
dtype: float64
i want to get this value in a data frame, with column name = ticker, and sharpe ratio so it should look like this
Ticker Sharpe
NOW 0.906136
BBY 0.667774
I want to get this in a data frame as I have several other print functions, like VAr etc, so I can merge them and then export the data frame to excel.
please help me how to get print output in a data frame in python.
import numpy as np
import pandas as pd
# Construct initial dataframe
df = pd.DataFrame({
'date': ['2013-0-30', '2013-10-01', '2013-10-02', '2013-10-03', '2013-10-04'],
'NOW': [np.nan, -0.008855, 0.015149, -0.002296, 0.043720],
'BBY': [np.nan, 0.012000, -0.007642, 0.000796, 0.012206],
})
df = df.set_index('date')
# Calculate Sharpe ratio
N = 252
sharpe = np.sqrt(N) * df.mean() / df.std()
# Transform Sharpe ratio data from Series to DataFrame
df2 = sharpe.to_frame('Sharpe')
df2.index.name = 'Ticker'
df2 = df2.reset_index()
which gives as result:
In [1]: df2
Out[1]:
Ticker Sharpe
0 NOW 8.061887
1 BBY 7.174034
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.