Momentum-Weighted Portfolio: Daily Log Return Statistics
Arrays & HashingAuto-graded · 18 test casesLast updated
Tests simulation of a daily rebalancing strategy where portfolio weights are proportional to positive asset returns, requiring correct timeline logic and statistical output.
Momentum-Weighted Portfolio: Daily Log Return Statistics
You are given a price matrix prices with shape N × T, where prices[i][t] is the closing price of asset i on day t (days are indexed 0 through T−1). You also receive an initial cash amount capital, though as you will find, it has no effect on the answer.
Strategy rules
Simple return for asset i on day t (for t ≥ 1):
r_i(t) = prices[i][t] / prices[i][t-1] − 1
Portfolio weights set at the close of day t:
- If every asset has
r_i(t) ≤ 0, hold 100% cash the next day. - Otherwise, allocate weight proportional to each asset's positive return:
w_i(t) = r_i(t) / Σ_{j: r_j(t) > 0} r_j(t)whenr_i(t) > 0w_i(t) = 0otherwise
Fractional shares are allowed and transaction costs are zero.
Timeline
There are exactly T−1 daily log return periods, one for each consecutive pair of days:
| Period | Portfolio held | Reason |
|---|---|---|
| day 0 → day 1 | 100% cash | No prior returns exist to set weights; log return = 0 |
| day 1 → day 2 | weights w(1) from r(1) | Rebalanced at close of day 1 |
| day t → day t+1 | weights w(t) from r(t) | Rebalanced at close of day t |
For any period t → t+1 where weights have been set, the portfolio's gross return is:
1 + Σ_i w_i(t) · r_i(t+1)
So the log return for that period is:
ln(1 + Σ_i w_i(t) · r_i(t+1))
For a cash-held period, the log return is exactly 0.
What to return
Compute the population mean and population standard deviation (divide by n, not n−1) of the T−1 log returns and return them as [mean_log_return, stddev_log_return].
If T ≤ 1 or there are no assets, return [0.0, 0.0].
Constraints
0 ≤ N ≤ 100(number of assets)0 ≤ T ≤ 500(number of days)- All prices are strictly positive floating-point values
- The price matrix is rectangular: every asset has exactly
Tprice entries capital > 0, but it does not affect the output- A return of exactly
0is not considered positive
Examples
Example 1
Input: momentum_weighted_portfolio_stats([[100, 110, 121], [100, 90, 99]], 1000)
Output: [0.04765508990216247, 0.04765508990216247]
Example 2
Input: momentum_weighted_portfolio_stats([[100, 90, 81], [100, 110, 121]], 500)
Output: [0.04765508990216247, 0.04765508990216247]
Example 3
Input: momentum_weighted_portfolio_stats([[10, 10, 11, 10], [20, 19, 19, 20]], 100)
Output: [-0.03177005993477496, 0.04492964963716485]
Hints
Hint 1
Sketch the timeline before writing any code. There are exactly T−1 log return periods. The very first one (day 0 → day 1) is always a cash period with log return 0, because no daily returns are observable until day 1.
Hint 2
The initial capital C never affects the answer. A fully rebalanced portfolio's gross return over one period equals the weighted sum of that period's gross returns, and the current portfolio value cancels out. You only need to track returns, not dollar amounts or share counts.
Hint 3
Use math.log1p(x) to compute ln(1 + x) instead of math.log(1 + x). For small daily returns it is significantly more numerically accurate. Also be careful to use population standard deviation (divide by n), and state that assumption clearly.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Get the timeline exactly right
The single biggest source of bugs here is off-by-one errors in the day index. Write it out explicitly before touching code.
There are T days (indices 0 through T−1) and therefore T−1 consecutive day-pairs, each producing one log return. That count is fixed and non-negotiable; the problem says "over all T−1 daily log returns."
The first period (day 0 → day 1) is always cash. At the close of day 0 we have no prior price data, so no returns are computable and no weights can be set. Its log return is ln(1) = 0.
For each subsequent period t → t+1 (where t runs from 1 to T−2 inclusive):
- Compute simple returns
r_i(t) = prices[i][t] / prices[i][t-1] − 1for all assets. These are known at the close of dayt. - Sum up only the positive returns:
pos_sum = Σ r_i(t) where r_i(t) > 0. - If
pos_sum ≤ 0, hold cash — log return is 0. - Otherwise, assign weight
w_i = r_i(t) / pos_sumto each asset with a positive return (zero to all others). - Compute the weighted portfolio return over the next day using prices at
t+1:port_ret = Σ w_i · (prices[i][t+1] / prices[i][t] − 1). - Append
log1p(port_ret)to the list.
Why capital C doesn't matter
At any point in time, the portfolio value is some scalar V_t. Over the next period the value becomes V_t · (1 + port_ret). The log return is ln(V_{t+1} / V_t) = ln(1 + port_ret), which has no V_t in it. Since V_0 = C, the starting capital scales every V_t equally and drops out of every log return. You never need to track dollars or share counts.
Why the solution is correct
- Weights are valid: positive returns divide by their own sum, giving non-negative weights that sum to 1. Cash periods also sum to 1 (100% in cash).
- No look-ahead bias:
w(t)only uses prices on daystandt−1, both available at the close of daytbefore the next day opens. - All T−1 periods accounted for: the initial cash period is explicitly prepended as
0.0, so the list always has exactly T−1 entries (when T ≥ 2). - Edge case T ≤ 1: there are no periods at all; return
[0.0, 0.0]. r = 0is not positive: the checkr > 0.0(strict) handles the edge case of flat prices correctly.
Statistics convention
Mean and standard deviation are both population statistics, dividing by n (the count of log returns, which equals T−1). This is the convention specified by the problem. If a sample standard deviation (divide by n−1) were needed instead, only one token changes.
math.log1p(x) is used in place of math.log(1 + x) for numerical accuracy when daily returns x are small.
Complexity
- Time: O(N · T). Each of the T−1 periods does O(N) work to compute returns, find the positive sum, and accumulate the weighted next-period return.
- Space: O(T) for storing the list of log returns. This can be reduced to O(1) using Welford's online algorithm for mean and variance, but O(T) is simpler and acceptable for the given constraints.
Reference solution
import math
from typing import List
def momentum_weighted_portfolio_stats(prices: List[List[float]], capital: float) -> List[float]:
n = len(prices)
if n == 0 or len(prices[0]) < 2:
return [0.0, 0.0]
t_count = len(prices[0])
# Period 0 -> 1 is always cash: log return = 0.
log_returns = [0.0]
# Periods 1 -> 2, 2 -> 3, ..., (T-2) -> (T-1).
# Weights at close of day t use returns r(t); applied over day t -> t+1.
for t in range(1, t_count - 1):
returns = [prices[i][t] / prices[i][t - 1] - 1.0 for i in range(n)]
positive_sum = sum(r for r in returns if r > 0.0)
if positive_sum <= 0.0:
log_returns.append(0.0)
continue
portfolio_return = 0.0
for i, r in enumerate(returns):
if r > 0.0:
weight = r / positive_sum
next_return = prices[i][t + 1] / prices[i][t] - 1.0
portfolio_return += weight * next_return
log_returns.append(math.log1p(portfolio_return))
mean = sum(log_returns) / len(log_returns)
variance = sum((x - mean) ** 2 for x in log_returns) / len(log_returns)
return [mean, math.sqrt(variance)]