Portfolio Turnover with Pandas

Viewed 604

I would like to compute the portfolio turnover for a monthly rebalanced portfolio that looks this:

df = pd.DataFrame({'Date': ['6/30/2015','6/30/2015','6/30/2015','7/30/2015','7/30/2015','7/30/2015'],'Ticker': ['AAPL','MSFT','IBM','AAPL','MSFT','AMZN']})
df['Date']=pd.to_datetime(df['Date'])

In particular, I would like to know for each month, how many of the positions in the portfolio were replaced. So for July it should show 1/3, since IBM was replaced with AMZN.

1 Answers

You can pivot and use shift to compare:

pivoted = df.assign(rank=df.groupby('Date').cumcount()).pivot('Date','rank','Ticker')

(pivoted!=pivoted.shift()).sum(1)/pivoted.shape[1]

Output:

Date
2015-06-30    1.000000
2015-07-30    0.333333
dtype: float64
Related