Calculate the contribution of each stock to the index
You have successfully built the value-weighted index. Let's now explore how it performed over the 2010-2016 period.
Let's also determine how much each stock has contributed to the index return.
This exercise is part of the course
Manipulating Time Series Data in Python
Exercise instructions
We have already imported pandas as pd and matplotlib.pyplot as plt for you. We have also loaded components and the index you worked with in the last exercise.
- Divide the last
indexvalue by the first, subtract 1 and multiply by 100. Assign the result toindex_returnand print it. - Select the
'Market Capitalization'column fromcomponents. - Calculate the total market cap for all components and assign this to
total_market_cap. - Divide the components' market cap by
total_market_capto calculate the component weights, assign it toweights, and printweightswith the values sorted in default (ascending) order. - Multiply
weightsby theindex_returnto calculate the contribution by component, sort the values in ascending order, and plot the result as a horizontal bar chart.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Calculate and print the index return here
index_return = ____
print(____)
# Select the market capitalization
market_cap = ____
# Calculate the total market cap
total_market_cap = ____
# Calculate the component weights, and print the result
weights = ____
print(____)
# Calculate and plot the contribution by component