Whats the rational for this line?

Calculate the daily percentage change of both the stocks

df_change = df.pct_change()

Drop the first row containing the null values

df_change.dropna(inplace=True)

Calculate the cumulative percentage returns of each stock

df_cumulative_returns = (df_change+1).cumprod()*100


Save the number of stocks in a variable

no_of_stocks = df_change.shape[1]

no_of_stocks



weights = cp.Variable(no_of_stocks)

weights.shape


Save the portfolio returns in a variable

portfolio_returns = (np.array(df_change)@weights)





final_portfolio_value = cp.sum(cp.log(1+portfolio_returns))

objective = cp.Maximize(final_portfolio_value)

constraints = [0.0 <= weights, cp.sum(weights) == 1]



problem = cp.Problem(objective, constraints)

The optimal objective value is returned by prob.solve().

problem.solve()

The optimal value for w is stored in w.value.

print(weights.value)







Whats the rational for  this line?


Calculate the cumulative percentage returns of each stock

df_cumulative_returns = (df_change+1).cumprod()*100



 

Cumulative returns help us understand how much our initial capital has grown through the backtesting period. 



The df_change contains the daily percentage change of the asset. 

We are adding 1, so that initially we assume that we have $1 dollar (assumed in ratio perspective) and then we use cumprod as it calculates the cumulative product of each row in the resulting DataFrame. This gives us the cumulative return for each day, as it multiplies together all the daily returns up to that point.

Note that we are assuming the profits are reinvested in the strategy, hence it is cumprod.



We multiply the result by 100 so that we can see the result in percentage terms. This helps us to calculate the cumulative returns, which is a useful metric for analysing the performance of an investment. In this way, we can see how much the strategy returns have grown or shrunk over time, and we can compare the performance of different strategies against each other.