I have multi-level column data like this:
price flag shares balance finalbalance
A B A B A B
100 100 0 .4 .6 40 60 100
80 150 0 .4 .6 32 90 122
90 120 1 .48 .54 43.2 64.8 108
So my problem is that of re-balance.
- Price column shows prices of stocks "A" and "B"
- flag column is either 0 or 1. When it's 0, we don't do anything. When it's 1 we rebalance the portfolio in a 40%:60% ratio. For example, at the start of the portfolio, $100 was divided into $40 and $60, and then the prices of the security went up/down. When the flag became = 1, we wanted to rebalance our total balance into 40%:60%. Since the total balance was $108 when the flag became 1, we divide the money into these stocks in the 40%:60% ratio, which was 43.2 and 64.8 depending on the price of that day for A and B.
How do I achieve this in python? Since its multi-level columns, I am not able to use ".loc" and ".at" commands.
This is what I was able to code:
tickers=['A','B']
ticker_weights = {
"A": 0.40,
"B": 0.60 }
for i in range(0,len(stock_data)):
if(stock_data.flag.iloc[i]==1):
for ticker in tickers:
stock_data['shares'][ticker].loc[i] = ticker_weights[ticker]*stock_data.finalbalance.iloc[i]