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 is a 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
index
value by the first, subtract 1 and multiply by 100. Assign the result toindex_return
and 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_cap
to calculate the component weights, assign it toweights
, and printweights
with the values sorted in default (ascending) order. - Multiply
weights
by theindex_return
to 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
This exercise is part of the course
Manipulating Time Series Data in Python
In this course you'll learn the basics of working with time series data.
This chapter combines the previous concepts by teaching you how to create a value-weighted index. This index uses market-cap data contained in the stock exchange listings to calculate weights and 2016 stock price information. Index performance is then compared against benchmarks to evaluate the performance of the index you created.
Exercise 1: Select index components & import dataExercise 2: Explore and clean company listing informationExercise 3: Select and inspect index componentsExercise 4: Import index component price informationExercise 5: Build a market-cap weighted indexExercise 6: Calculate number of shares outstandingExercise 7: Create time series of market valueExercise 8: Calculate & plot the composite indexExercise 9: Evaluate index performanceExercise 10: Calculate the contribution of each stock to the indexExercise 11: Compare index performance against benchmark IExercise 12: Compare index performance against benchmark IIExercise 13: Index correlation & exporting to ExcelExercise 14: Visualize your index constituent correlationsExercise 15: Save your analysis to multiple excel worksheetsExercise 16: Congratulations!What is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.