{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Stocks, volatility, and diversification

\n",
"\n",
"(Sethna, \"Entropy, Order Parameters, and Complexity\", ex. 2.11)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Stock prices are fairly good approximations to random walks. The Standard and Poor's 500 Index is a weighted average of the prices of five hundred large companies in the United States stock market.\n",
"\n",
"Make sure you download SandPConstantDollars.dat from the exercises Web site. Each line represents a working weekday. The first column is time $t$ in days since mid-October 1982, and the second column is the Standard and Poor's index $SP(t)$ for that day, corrected for inflation.\n",
"\n",
"Import packages"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%pylab inline\n",
"from scipy import *"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Read in the file of Standard and Poor's average stock price (SP) in constant dollars (corrected for inflation), versus time t \n",
"\n",
"Convert from \"list\" to \"array\" form (arrays can be multiplied and added, etc.)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"t, SP = array(loadtxt(\"SandPConstantDollars.dat\").transpose())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Are the random fluctuations in the stock-market due to external events?\n",
"\n",
"Plot SP versus t\n",
"\n",
"Note 9/11/01 is day 6903: is it the cause for the post-2000 drop?\"\n",
"\n",
"Zoom in and see: did the terrorist attach on the World Trade Center\n",
"trigger the stock market downturn, or was it just a small extra dip in\n",
"an overall pattern?\n",
"\n",
"You can plot a subset of the data using 'slicing': for a list or array v, v[m:n] gives back the elements in the range [m,n) -- starting at m and ending at n-1. The interesting region around the attack at day 6903 is around trading day 4750 (remember weekends count as days, but not as trading days), and ends around 4900."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"plot(...);\n",
"figure()\n",
"tradeDayMin, tradeDayMax = (...)\n",
"plot(t[tradeDayMin:tradeDayMax], SP[...]);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Sometimes large fluctuations are due to external events; the fluctuations in ecological populations and species are also quite random, but the dinosaur extinction was surely caused by a meteor."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What is the distribution of step sizes in stock prices? This depends on how we define a step; do we ask how much it has changed after a year, a month, a week, or a day? A technical question arises: do we measure time in days, or trading days. We shall follow the finance community, and consider only trading days. \n",
"\n",
"Define a function P(lag) giving the percentage change after a 'lag' of trading days.\n",
"\n",
"Use slicing to do all the comparisons in one array operation.\n",
" For a list or array v, v[m:n] gives back the elements in the range [m,n) \n",
" -- starting at m and ending at n-1. Python also makes the useful convention\n",
" that v[:,n] starts at the beginning of the list, v[m:] ends at the end, and \n",
" v[:,-p] 'drops' the last p elements.\n",
" \n",
"Also use the scipy convention that arithmetic acts element-by-element on arrays. So for two\n",
"arrays w and v of the same length, \n",
"\n",
" w*v = array([w[0]*v[0],w[1]*v[1], ...]), \n",
" \n",
"and similarly for w/v, w+v, and w-v. (The last two are the same as the math conventions for vectors.) Also, adding and subtracting scalars from arrays is done elementwise, so \n",
"\n",
" v+5 = array([v[0]+5, v[1]+5, ...]).\n",
"\n",
"Loops are very slow in interpreted languages like Python, so learning to do things with array operations like these is strongly recommended."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def P(lag):\n",
" \"\"\"\n",
" Function which returns a list of percentage changes after a number\n",
" \"lag\" of trading days. \n",
" P(1) gives the daily percentage changes, P(5) the weekly changes, P[252] the yearly changes, etc.\n",
" \n",
" To find the ratio of values of an array v of length N after a shift of t, one could use\n",
" v[t:N]/v[0:N-t]\n",
" or\n",
" v[t:]/v[:-t]\n",
" \"\"\"\n",
" ratios = .../...\n",
" P = ...*(...-...)\n",
" return P"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plot a normed histogram using 50 bins for daily, weekly, and yearly percentage changes. \n",
"Which of the three represents a reasonable time to stay invested in the Standard and Poor's index (during which you have a mean percentage growth larger than a tiny fraction of the fluctuations)? Why do the yearly changes look so much more complicated than the other distributions?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"hist(P(252), bins=50, normed=True);\n",
"hist(...);\n",
"hist(...);\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Some of the distributions you found above should look quite Gaussian, as predicted from our Green's function analysis of random walks (or more generally, to the central limit theorem). Here the random walk is in the percentage return -- in the logarithm of the fractional price change. The logarithm of a Gaussian distribution is an inverted parabola. Do a log plot of the histogram of weekly price changes:\n",
"\n",
" hist(..., log=True)\n",
"\n",
"Are there 'fat tails' (more large changes than predicted by the inverted parabola you would expect from a Gaussian)? (Hint: P(lag).mean() and P(lag).std() may be useful in generating the Gaussian fit to the data.)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"lag = 5\n",
"hist(P(...), ..., log=True);\n",
"x = arange(-7.,7.,0.1);\n",
"sig = P(lag). ...\n",
"x0 = ...\n",
"gauss = (1./...)*exp(...)\n",
"plot(x,gauss,'r');"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Make an array of lag times running from one to 100, and an array of volatilities using std(). Plot volatility and volatility squared versus lag.\n",
"\n",
"Hint: [blah(lag) for lag in lags] produces a list of blah(lag[0]), blah(lag[1]), ..., and array([blah(lag) for lag in lags]) will change the list to an array (which then can be squared using **2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"lags = arange(1,100)\n",
"volatility = array([... for ...])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"plot(...);"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"plot(...);"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}