import yfinance as yf
import pandas as pd
# Download historical data
df = yf.download(stocks.to_list(), start='2022-08-01')
df_close = df['Adj Close']
df_dret = df_close.pct_change()
df_wret = (df_dret + 1).resample('W').prod() - 1
df_mret = (df_dret + 1).resample('M').prod() - 1
# Calculate 12-month rolling returns
df_mret_12 = df_mret.rolling(12).apply(lambda x: (x + 1).prod() - 1).dropna()
print('month wise : \n',df_mret_12.iloc[:,0])
# Calculate 55 weeks rolling return
df_wret_55 = df_wret.rolling(55).apply(lambda x: (x + 1).prod() - 1).dropna()
print('week wise :\n',df_wret_55.iloc[:,0])
# Calculate 252-days rolling return
df_dret_252 = df_dret.rolling(252).apply(lambda x: (x + 1).prod() - 1)
print('day wise :\n',df_dret_252.iloc[:,0:2])
m_top10 = df_mret_12.iloc[-2:].apply(lambda row: row.nlargest(10), axis=1)
print('top 10 with date ',m_top10.index[0],'\n')
print(m_top10.iloc[0].sort_values(ascending=False).dropna(axis=0))
print('top 10 with date ',m_top10.index[1],'\n')
print(m_top10.iloc[1].sort_values(ascending=False).dropna(axis=0))
Result: