Level 1 Portfolio values
You backtest a simple momentum fund. prices[i][t] is the closing price of stock i on day t (N stocks, T days, all positive integers). You start on day 0 with capital in cash. Fractional shares are allowed and trading is free.
At each close from day 1 onward you rebalance the entire portfolio value using that day's return of each stock, r_i = prices[i][t] / prices[i][t-1] - 1:
- Stocks with
r_i > 0get a share of the money proportional tor_i. - Stocks with
r_i <= 0get nothing. - If no stock has a positive return, everything sits in cash until the next close.
On day 0 there are no returns yet, so you hold cash through day 1. Holdings keep their shares between closes, so their value moves with the prices until you rebalance again.
Write
def portfolio_values(prices: list[list[int]], capital: int) -> list[Fraction]
returning the portfolio value at each day's close (before rebalancing, which doesn't change the value), as exact fractions.Fraction values. The list has length T and starts with capital.
Example: prices = [[10, 12, 15, 12], [20, 21, 20, 22]], capital = 2100.
- Day 1: stock 0 returned +20%, stock 1 +5%. Split 4:1, so 1680 in stock 0 and 420 in stock 1. The value is still 2100 (cash was held from day 0).
- Day 2: stock 0 is worth
1680 * 15/12 = 2100, stock 1420 * 20/21 = 400, total 2500. Only stock 0 went up, so all 2500 goes into it. - Day 3:
2500 * 12/15 =2000.
Answer: [2100, 2100, 2500, 2000].
Constraints: 1 <= N <= 5, 1 <= T <= 30 for this level.