Ranking Stocks based on Momentum - Last day of the month

Hi,



I would like to rank stocks based on momentum on end of each month and maintain the rank for entire nexy month. can some one help me?



import pandas as pd

import math

import numpy as np

import matplotlib.pyplot as plt

import datetime as dt



df = pd.read_csv("E:\StockData.csv",index_col=[0])

df.index=pd.to_datetime(df.index,format='%m/%d/%y').date


Create a dataframe called df_change to hold the future returns of the stocks

df_change = df.pct_change().shift(-1)

#df_change = df.pct_change()

Drop the rows containing the null values

df_change.dropna(inplace=True)


Create a variable t to signify the lookback period to calculate the average price of the stock.

quanterly_working_days = 21 * 3


Calculate the momentum values for each stock by subtracting the stock price form the mean value

momentum_factor = df/ df.rolling(quanterly_working_days).mean()


here I want to rank at end of each month and have same rank for entire next month

momentum_rank = momentum_factor.rank(axis=1,ascending=False)

Hi Vetrivel,



Thank you for writing to us. You can try replacing the last 2 lines of your code with the following:


Calculate the momentum values for each stock by subtracting the stock price form the mean value

momentum_factor = df/ df.rolling(quanterly_working_days).mean()

momentum_factor.index=pd.to_datetime(momentum_factor.index, format='%Y-%m-%d')


here I want to rank at end of each month and have same rank for entire next month

momentum_rank = momentum_factor.rank(axis=1)

ranks=momentum_rank.groupby(pd.Grouper(freq="M")).tail(1)


Create new column to contain ranks

df[df.columns+'rank']=ranks

df.fillna(method='ffill',inplace=True)

Thank you for the quick reply. It is working. I changed the frequency to Quarter by freq="M". Can we have quarterly like fenruary to april, may to july etc… instaed of jan to march, apr to jun.

Hi Vetrivel,



Replace the freq parameter by specifying the name of the last month in the series, as shown below.



freq='Q-JAN'



Remember that you need to mention the name of the last month of your last quarter. So if you want the first quarter to start from February, then you need to specify JAN. 



Hope this helps. 

Thanks a lot. It works.