CommencerCommencer gratuitement

Make features and targets

To use machine learning to pick the best portfolio, we need to generate features and targets. Our features were just created in the last exercise – the exponentially weighted moving averages of prices. Our targets will be the best portfolios we found from the highest Sharpe ratio.

We will use pandas' .iterrows() method to get the index, value pairs for the ewma_monthly DataFrame. We'll set the current value of ewma_monthly in the loop to be our features. Then we'll use the index of the best Sharpe ratio (from max_sharpe_idxs) to get the best portfolio_weights for each month and set that as a target.

Cet exercice fait partie du cours

Machine Learning for Finance in Python

Afficher le cours

Instructions

  • Use the .iterrows() method with ewma_monthly to iterate through the index, value in the loop.
  • Use the date in the loop and best_idx to index portfolio_weights to get the ideal portfolio weights based on the best Sharpe ratio.
  • Append the ewma to the features.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

targets, features = [], []

# Create features from price history and targets as ideal portfolio
for date, ewma in ewma_monthly.____:

    # Get the index of the best sharpe ratio
    best_idx = max_sharpe_idxs[date]
    targets.append(portfolio_weights[____][____])
    features.append(____)  # add ewma to features

targets = np.array(targets)
features = np.array(features)
print(targets[-5:])
Modifier et exécuter le code