Get startedGet started for free

Evaluate returns

Let's now see how our portfolio selection would perform as compared with just investing in the SPY. We'll do this to see if our predictions are promising, despite the low R\(^2\) value.

We will set a starting value for our investment of $1000, then loop through the returns from our predictions as well as from SPY. We'll use the monthly returns from our portfolio selection and SPY and apply them to our starting cash balance. From this we will get a month-by-month picture of how our investment is doing, and we can see how our predictions did overall vs the SPY. Next, we can plot our portfolio from our predictions and compare it to SPY.

This exercise is part of the course

Machine Learning for Finance in Python

View Course

Exercise instructions

  • Set the first list entries of both algo_cash and spy_cash to the same amount (cash).
  • Multiply the cash in our test_returns loop by 1 + r in order to apply the returns to our cash.
  • As with the test_returns loop, in the SPY performance loop, append cash to spy_cash after multiplying by 1 + r to add the returns to cash.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Calculate the effect of our portfolio selection on a hypothetical $1k investment
cash = 1000
algo_cash, spy_cash = [cash], ____  # set equal starting cash amounts
for r in test_returns:
    cash *= 1 + r
    algo_cash.append(cash)

# Calculate performance for SPY
cash = 1000  # reset cash amount
for r in returns_monthly['SPY'].iloc[train_size:]:
    cash ____ ____
    ____

print('algo returns:', (algo_cash[-1] - algo_cash[0]) / algo_cash[0])
print('SPY returns:', (spy_cash[-1] - spy_cash[0]) / spy_cash[0])
Edit and Run Code