Get startedGet started for free

Get best Sharpe ratios

We need to find the "ideal" portfolios for each date so we can use them as targets for machine learning. We'll loop through each date in portfolio_returns, then loop through the portfolios we generated with portfolio_returns[date]. We'll then calculate the Sharpe ratio, which is the return divided by volatility (assuming a no-risk return of 0).

We use enumerate() to loop through the returns for the current date (portfolio_returns[date]) and keep track of the index with i. Then we use the current date and current index to get the volatility of each portfolio with portfolio_volatility[date][i]. Finally, we get the index of the best Sharpe ratio for each date using np.argmax(). We'll use this index to get the ideal portfolio weights soon.

This exercise is part of the course

Machine Learning for Finance in Python

View Course

Exercise instructions

  • Using enumerate(), enumerate the portfolio_returns for each date in the loop.
  • For the current date in the loop, append to the sharpe_ratio dictionary entry with the return (ret) divided by portfolio_volatility for the current date and current i in the loops.
  • Set the value for the current date's max_sharpe_idxs to be the index of the maximum Sharpe ratio using np.argmax().

Hands-on interactive exercise

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

# Empty dictionaries for sharpe ratios and best sharpe indexes by date
sharpe_ratio, max_sharpe_idxs = {}, {}

# Loop through dates and get sharpe ratio for each portfolio
for date in portfolio_returns.keys():
    for i, ret in enumerate(portfolio_returns[____]):
    
        # Divide returns by the volatility for the date and index, i
        sharpe_ratio.setdefault(date, []).append(____ / portfolio_volatility[date][____])

    # Get the index of the best sharpe ratio for each date
    max_sharpe_idxs[date] = np.argmax(sharpe_ratio[____])

print(portfolio_returns[date][max_sharpe_idxs[date]])
Edit and Run Code