below is how the data is structured
I'm sure this is simple, but as a newbie to python, I'm having trouble figuring out how to iterate over variables.
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 35 entries, 2021-02-25 to 2021-04-15
Data columns (total 11 columns):
dtypes: float64(11)
suppose I wanted to loop the code below so it performs the function on all the columns and outputs df. How would I do that?
n_days = 6
n=len(prices)- n_days
dnum = np.arange(1,n, 1).tolist()
a_list = []
b_list = []
c_list = []
d_list = []
e_list = []
f_list = []
for x in dnum:
s = x
i = n_days+x
new_prices = prices[s:i]
returns = new_prices['fngu'].to_returns().dropna()
sharp_1 = returns.calc_sharpe_ratio(nperiods=365)
returns = new_prices['soxl'].to_returns().dropna()
sharp_2 = returns.calc_sharpe_ratio(nperiods=365)
returns = new_prices['spxl'].to_returns().dropna()
sharp_3 = returns.calc_sharpe_ratio(nperiods=365)
returns = new_prices['fas'].to_returns().dropna()
sharp_4 = returns.calc_sharpe_ratio(nperiods=365)
returns = new_prices['utsl'].to_returns().dropna()
sharp_5 = returns.calc_sharpe_ratio(nperiods=365)
date = prices.index[i]
a_list.append(date)
b_list.append(sharp_1)
c_list.append(sharp_2)
d_list.append(sharp_3)
e_list.append(sharp_4)
f_list.append(sharp_5)
df = pd.DataFrame({'Date': a_list, 'fngu': b_list, 'soxl': c_list, 'spxl': d_list, 'fas': e_list, 'utsl': f_list})
del a_list, b_list, c_list, d_list, e_list, f_list
I tried using concat and iteritems function but I am too much of a noob for that
EDIT:: I sort of came up with solution from other posts,
r_list = []
for x in dnum:
s = x
i = n_days+x
new_prices = prices[s:i]
returns = new_prices.to_returns().dropna()
sharp = returns.calc_sharpe_ratio(nperiods=365)
sharp['Date'] = prices.index[i]
s = pd.DataFrame(sharp)
s= s.transpose()
r_list.append(s)
df = pd.concat(r_list)
df.Date = pd.to_datetime(df.Date)
df = df.set_index('Date')
This works for what I need but I would like to learn the most efficient way to do this type of loop or something else.