| 1 |
{ |
| 2 |
"cells": [ |
| 3 |
{ |
| 4 |
"cell_type": "markdown", |
| 5 |
"metadata": {}, |
| 6 |
"source": [ |
| 7 |
"### US Equity market performance from 1995 to 2021\n", |
| 8 |
"In this visualization we'll look S&P 500 Index performance from 1995 to 2021. The visualization consists of two charts:\n", |
| 9 |
"* Time Series Chart of Index prices\n", |
| 10 |
"* Histogram of the log returns\n", |
| 11 |
"\n", |
| 12 |
"We'll use the [Fast Interval Selector](../Interactions/Selectors.ipynb) to quickly select different time slices and perform time series analysis on the selected slice (in this case, displaying the total return and the distribution of log returns). **Click on the time series chart to activate the interval selector!**\n", |
| 13 |
"\n", |
| 14 |
"Fun things to try:\n", |
| 15 |
"1. `FastIntervalSelector` responds to mouse moves! Move the mouse pointer up to expand the interval, down to contract the interval. Single click toggles between freezing/unfreezing the window length. Double click totally freezes the interval selector. Move the interval selector to perform quick visual time series analysis!\n", |
| 16 |
"2. Notice that the color of the return label changes with the sign of the total return (red for negative returns and green for positive returns)\n", |
| 17 |
"3. What was the index performance from 1995-2005? 2000-2010? 2010-2020?\n", |
| 18 |
"4. Does the return distribution have fat tails? (especially during 2008 financial crisis, 2020 covid crisis)" |
| 19 |
] |
| 20 |
}, |
| 21 |
{ |
| 22 |
"cell_type": "code", |
| 23 |
"execution_count": null, |
| 24 |
"metadata": {}, |
| 25 |
"outputs": [], |
| 26 |
"source": [ |
| 27 |
"import numpy as np\n", |
| 28 |
"import pandas as pd\n", |
| 29 |
"\n", |
| 30 |
"import ipywidgets as widgets\n", |
| 31 |
"from bqplot import DateScale, LinearScale\n", |
| 32 |
"import bqplot.pyplot as plt\n", |
| 33 |
"from bqplot.interacts import FastIntervalSelector" |
| 34 |
] |
| 35 |
}, |
| 36 |
{ |
| 37 |
"cell_type": "code", |
| 38 |
"execution_count": null, |
| 39 |
"metadata": {}, |
| 40 |
"outputs": [], |
| 41 |
"source": [ |
| 42 |
"format_date = lambda d: d.strftime('%m/%d/%Y')\n", |
| 43 |
"\n", |
| 44 |
"spx_prices = pd.read_csv('spx_prices.csv', index_col=0, parse_dates=True, squeeze=True)\n", |
| 45 |
"log_returns = np.log(spx_prices / spx_prices.shift(1))\n", |
| 46 |
"dates = spx_prices.index" |
| 47 |
] |
| 48 |
}, |
| 49 |
{ |
| 50 |
"cell_type": "code", |
| 51 |
"execution_count": null, |
| 52 |
"metadata": { |
| 53 |
"scrolled": true |
| 54 |
}, |
| 55 |
"outputs": [], |
| 56 |
"source": [ |
| 57 |
"fig_title_tmpl = 'S&P Index Prices (from {start} to {end})'\n", |
| 58 |
"fig_title = fig_title_tmpl.format(start=format_date(dates[0]), \n", |
| 59 |
" end=format_date(dates[-1]))\n", |
| 60 |
"time_series_fig = plt.figure(title=fig_title,\n", |
| 61 |
" layout=widgets.Layout(width='1300px', height='500px'))\n", |
| 62 |
"\n", |
| 63 |
"plt.scales(scales={'x': DateScale()})\n", |
| 64 |
"axes_options = {'y': {'tick_format': ','}}\n", |
| 65 |
"time_series = plt.plot(dates, spx_prices, colors=['dodgerblue'], \n", |
| 66 |
" stroke_width=1.5, axes_options=axes_options)\n", |
| 67 |
"return_label = plt.label([], x=[], y=[spx_prices.max() * .9], \n", |
| 68 |
" align='middle', default_size=36, \n", |
| 69 |
" font_weight='bolder', colors=['green'])\n", |
| 70 |
"trend_line = plt.plot([], [])\n", |
| 71 |
"intsel = FastIntervalSelector(scale=time_series.scales['x'], marks=[time_series])\n", |
| 72 |
"time_series_fig.interaction = intsel\n", |
| 73 |
"\n", |
| 74 |
"hist_fig = plt.figure(title='Histogram Of Returns',\n", |
| 75 |
" layout=widgets.Layout(width='900px',\n", |
| 76 |
" height='450px',\n", |
| 77 |
" margin='0px 150px 0px 150px'))\n", |
| 78 |
"plt.scales(scales={'x': LinearScale(min=-.1, max=.1)})\n", |
| 79 |
"hist = plt.hist(log_returns, colors=['salmon'], bins=75)\n", |
| 80 |
"for axis in hist_fig.axes:\n", |
| 81 |
" axis.grid_lines = 'none'\n", |
| 82 |
" if axis.orientation != 'vertical':\n", |
| 83 |
" axis.tick_format = '.0%'\n", |
| 84 |
"\n", |
| 85 |
"def update_hist(*args):\n", |
| 86 |
" selected_ix = time_series.selected\n", |
| 87 |
" if selected_ix is not None:\n", |
| 88 |
" s, e = selected_ix[0], selected_ix[-1]\n", |
| 89 |
" spx_prices_slice = spx_prices[s:e]\n", |
| 90 |
" pct_return = spx_prices[e] / spx_prices[s] - 1\n", |
| 91 |
" \n", |
| 92 |
" # update the position of the total return label\n", |
| 93 |
" with return_label.hold_sync():\n", |
| 94 |
" return_label.text = ['{:.0%}'.format(pct_return)]\n", |
| 95 |
" return_label.x = [time_series.x[(s + e) // 2]]\n", |
| 96 |
" return_label.colors = ['red'] if pct_return < 0. else ['green']\n", |
| 97 |
" \n", |
| 98 |
" time_series_fig.title = fig_title_tmpl.format(start=format_date(dates[s]),\n", |
| 99 |
" end=format_date(dates[e]))\n", |
| 100 |
" # update hist with returns\n", |
| 101 |
" hist.sample = np.log(spx_prices_slice / spx_prices_slice.shift(1))\n", |
| 102 |
"\n", |
| 103 |
"time_series.observe(update_hist, 'selected')\n", |
| 104 |
"widgets.VBox([time_series_fig, hist_fig])" |
| 105 |
] |
| 106 |
} |
| 107 |
], |
| 108 |
"metadata": { |
| 109 |
"kernelspec": { |
| 110 |
"display_name": "Python 3", |
| 111 |
"language": "python", |
| 112 |
"name": "python3" |
| 113 |
}, |
| 114 |
"language_info": { |
| 115 |
"codemirror_mode": { |
| 116 |
"name": "ipython", |
| 117 |
"version": 3 |
| 118 |
}, |
| 119 |
"file_extension": ".py", |
| 120 |
"mimetype": "text/x-python", |
| 121 |
"name": "python", |
| 122 |
"nbconvert_exporter": "python", |
| 123 |
"pygments_lexer": "ipython3", |
| 124 |
"version": "3.8.2" |
| 125 |
} |
| 126 |
}, |
| 127 |
"nbformat": 4, |
| 128 |
"nbformat_minor": 2 |
| 129 |
} |