I have am trying to make a simple stock portfolio tracker. I start with $100k dollars and invest based on weights in two stocks. Each month, I want to sell the stock and then set the new starting dollars (shares bought in last period * current price) and reinvest in the two stocks again based on this months weights.
I figured out how to calculate the Shares bought each period thanks to some previous SO help, but I'm have trouble update the starting balance for each date. I think due to order of operations, it needs to be done as a loop, but having trouble getting the shift to work.
Start of my code:
import pandas as pd
from datetime import datetime
df = pd.DataFrame(data=[[datetime(year=2017, day=01, month=01), 100000, 'AAPL', 0.6, 1000],
[datetime(year=2017, day=01, month=01), 100000, 'GOOG', 0.4, 1200],
[datetime(year=2017, day=01, month=02), 100000, 'AAPL', 0.7, 1400],
[datetime(year=2017, day=01, month=02), 100000, 'GOOG', 0.3, 1300],
[datetime(year=2017, day=01, month=03), 100000, 'AAPL', 0.8, 980],
[datetime(year=2017, day=01, month=03), 100000, 'GOOG', 0.2, 1400]
],
columns=['Date', 'Dollars Available', 'Stock', 'Weight', 'Price'])
df = df.set_index(['Date', 'Dollars Available', 'Stock'])
df['Shares Bought'] = (df.index.get_level_values('Dollars Available') * df['Weight']).values / df['Price'].values
So far, I've gotten to here. As you can see, the starting balance is the same for each date.
Weight Price Shares Bought
Date Dollars Available Stock
2017-01-01 100000 AAPL 0.6 1000 60.000000
GOOG 0.4 1200 33.333333
2017-02-01 100000 AAPL 0.7 1400 50.000000
GOOG 0.3 1300 23.076923
2017-03-01 100000 AAPL 0.8 980 81.632653
GOOG 0.2 1400 14.285714
Desired Output:
Weight Price Shares Bought
Date Dollars Available Stock
2017-01-01 10000.00 AAPL 0.6 1000 60.00
GOOG 0.4 1200 33.33
2017-02-01 127333.33 AAPL 0.7 1400 63.66
GOOG 0.3 1300 29.38
2017-03-01 103531.79 AAPL 0.8 980 73.95
GOOG 0.2 1400 22.19