mirror of
https://github.com/bspeice/speice.io
synced 2024-11-15 06:28:10 -05:00
995 lines
353 KiB
Plaintext
995 lines
353 KiB
Plaintext
|
{
|
||
|
"cells": [
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Or, being suspicious of market insiders.\n",
|
||
|
"\n",
|
||
|
"---\n",
|
||
|
"\n",
|
||
|
"Use the button below to show the code I've used to generate this article. Because there is a significant amount more code involved than most other posts I've written, it's hidden by default to allow people to concentrate on the important bits."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 1,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"text/html": [
|
||
|
"<script>\n",
|
||
|
"code_show=true; \n",
|
||
|
"function code_toggle() {\n",
|
||
|
" if (code_show){\n",
|
||
|
" $('div.input').hide();\n",
|
||
|
" } else {\n",
|
||
|
" $('div.input').show();\n",
|
||
|
" }\n",
|
||
|
" code_show = !code_show\n",
|
||
|
"} \n",
|
||
|
"$( document ).ready(code_toggle);\n",
|
||
|
"</script>\n",
|
||
|
"<form action=\"javascript:code_toggle()\"><input type=\"submit\" value=\"Click here to toggle on/off the raw code.\"></form>"
|
||
|
],
|
||
|
"text/plain": [
|
||
|
"<IPython.core.display.HTML object>"
|
||
|
]
|
||
|
},
|
||
|
"execution_count": 1,
|
||
|
"metadata": {},
|
||
|
"output_type": "execute_result"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"from IPython.display import HTML\n",
|
||
|
"\n",
|
||
|
"HTML('''<script>\n",
|
||
|
"code_show=true; \n",
|
||
|
"function code_toggle() {\n",
|
||
|
" if (code_show){\n",
|
||
|
" $('div.input').hide();\n",
|
||
|
" } else {\n",
|
||
|
" $('div.input').show();\n",
|
||
|
" }\n",
|
||
|
" code_show = !code_show\n",
|
||
|
"} \n",
|
||
|
"$( document ).ready(code_toggle);\n",
|
||
|
"</script>\n",
|
||
|
"<form action=\"javascript:code_toggle()\"><input type=\"submit\" value=\"Click here to toggle on/off the raw code.\"></form>''')"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"# The Market Just Knew\n",
|
||
|
"\n",
|
||
|
"I recently saw two examples of stock charts that have kept me thinking for a while. And now that the semester is complete, I finally have enough time to really look at them and give them the treatment they deserve. The first is good old Apple:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 2,
|
||
|
"metadata": {
|
||
|
"collapsed": false,
|
||
|
"scrolled": true
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAXQAAAEKCAYAAAACS67iAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3Xt8XHWd//HXu1D40bRJ0yJJtaUtClJQEFbkKgRdtsIu\nFwUR+CEg6HpDWDSr6PrbpojKJeKusAishYJSFcUtKIKAENyiqCsod+RiWygkwLaQNlwK6ef3xzmJ\n0+lMMrnMzMnk/Xw85pGZc75zvp85mfnMd77n+z1HEYGZmY19E6odgJmZjQ4ndDOzGuGEbmZWI5zQ\nzcxqhBO6mVmNcEI3M6sRTujjlKQTJf13her6tqR/qURdZuOZE/oYIKlD0mpJE0d508OahJDG87Kk\nbknPSrpWUlPRSiI+GRFfHX6YBWP4kKSHJb0oqVPSFZIm55WZIenJ9P6nJf1e0iuSLi+yzTMlnS1p\nT0k3S/pfSV2SfiipOa/suZKel/ScpHPy1p0l6V5Jr0n61wL1bC3pakkvpHV8dwT7YYGk9en/Ym36\nd05emb0k3VlKbGmZSyR9VNIhkv5b0hpJT0u6TFJdTrktJF2e/g+elnRG3nYuTf9HvZJOKFDPXEk/\nzXkfnZNfxobGCT3jJM0G9gM2AIdVOZ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E7qZWY1w\nQjczqxFO6GZmNcIJ3cysRjihm5nVCCd0M7Ma4YRuZiO2ePHiIS238nBCN7MRW758eenLneTLxgnd\nrEpqvfXa3NxMe3v7pitOPRWamysf0DjghG5WJcVatWNRe3s7zXlJuquri56enk0L9/RAV1eFIhtf\nNq92AGY29vX09BRO3lZ
|
||
|
"text/plain": [
|
||
|
"<matplotlib.figure.Figure at 0x1fae3a9b0f0>"
|
||
|
]
|
||
|
},
|
||
|
"metadata": {},
|
||
|
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"from secrets import QUANDL_KEY\n",
|
||
|
"import matplotlib.pyplot as plt\n",
|
||
|
"from matplotlib.dates import date2num\n",
|
||
|
"from matplotlib.finance import candlestick_ohlc\n",
|
||
|
"from matplotlib.dates import DateFormatter, WeekdayLocator,\\\n",
|
||
|
" DayLocator, MONDAY\n",
|
||
|
"import quandl\n",
|
||
|
"from datetime import datetime\n",
|
||
|
"import pandas as pd\n",
|
||
|
"%matplotlib inline\n",
|
||
|
"\n",
|
||
|
"def fetch_ticker(ticker, start, end):\n",
|
||
|
" # Quandl is currently giving me issues with returning\n",
|
||
|
" # the entire dataset and not slicing server-side.\n",
|
||
|
" # So instead, we'll do it client-side!\n",
|
||
|
" q_format = '%Y-%m-%d'\n",
|
||
|
" ticker_data = quandl.get('YAHOO/' + ticker,\n",
|
||
|
" start_date=start.strftime(q_format),\n",
|
||
|
" end_date=end.strftime(q_format),\n",
|
||
|
" authtoken=QUANDL_KEY)\n",
|
||
|
" return ticker_data\n",
|
||
|
"\n",
|
||
|
"def ohlc_dataframe(data, ax=None):\n",
|
||
|
" # Much of this code re-used from:\n",
|
||
|
" # http://matplotlib.org/examples/pylab_examples/finance_demo.html\n",
|
||
|
" if ax is None:\n",
|
||
|
" f, ax = plt.subplots()\n",
|
||
|
" \n",
|
||
|
" vals = [(date2num(date), *(data.loc[date]))\n",
|
||
|
" for date in data.index]\n",
|
||
|
" candlestick_ohlc(ax, vals)\n",
|
||
|
" \n",
|
||
|
" mondays = WeekdayLocator(MONDAY)\n",
|
||
|
" alldays = DayLocator()\n",
|
||
|
" weekFormatter = DateFormatter('%b %d')\n",
|
||
|
" ax.xaxis.set_major_locator(mondays)\n",
|
||
|
" ax.xaxis.set_minor_locator(alldays)\n",
|
||
|
" ax.xaxis.set_major_formatter(weekFormatter)\n",
|
||
|
" return ax\n",
|
||
|
"\n",
|
||
|
"AAPL = fetch_ticker('AAPL', datetime(2016, 3, 1), datetime(2016, 5, 1))\n",
|
||
|
"ax = ohlc_dataframe(AAPL)\n",
|
||
|
"plt.vlines(date2num(datetime(2016, 4, 26, 12)),\n",
|
||
|
" ax.get_ylim()[0], ax.get_ylim()[1],\n",
|
||
|
" color='b',\n",
|
||
|
" label='Earnings Release')\n",
|
||
|
"plt.legend(loc=3)\n",
|
||
|
"plt.title(\"Apple Price 3/1/2016 - 5/1/2016\");"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"The second chart is from Facebook:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 3,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAXYAAAEKCAYAAAAGvn7fAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3XmcFPWd//HXGxCVAYZDndGAgEbiETUab00cj4jGn1c0\nRlgPjJtj/bm6xEmibjYM2WiMjia/jXGjmxG8iDGaFS88UAfFKzEeiAdBDYKYGTUMwoyKOHx+f1T1\nWNPTPd0z3T3dXf15Ph79mO5vXZ+qqf70t771rSqZGc455+JjULEDcM45l1+e2J1zLmY8sTvnXMx4\nYnfOuZjxxO6cczHjid0552LGE7tzzsWMJ/aYk/SYpNML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cl8INlpakgwjax24ws93CssOBh81so6RLCWpu\nF4a/2K1m1hL+It9vZuPSz9254pN0P3C5mfXWBJEYd2vgaTNLbqYqe5KWEvx4v5bFuPsTbLODCh+Z\n66uMTTFmtoigNhQtW2BB8wAE3dPGheUvWHixjQXdpTYL2+2cK2UPERzxZGMkwcVEsRI2e/w2m6Qe\n2gikvW7AFVfGGjsEbW3AXYkae9KwO4FbLDhbHy0/ieDKvSPyFaxzzrnMhuQysaR/BzakSOq7AD8D\nvpLL/J1zzvVdvxO7pOkEZ8UPTSofx6fdnZb3Mr13VXLOuX4ws966D2fd3THRnzr4IB0JfB841szW\nR8qrCS7Q+KGZPdVjLklmzpzZ42xuvsvSlR988MEFX3ZfYvR4+va/8njKK56+fDdLIR4ofjzpYsxG\nxsQuaS5Bn+bJCm60dCbB1WrDgQcV3HTq6nD0cwguJvmxgps2PRveIyKlurq6gpelK584cWJR4kkX\no8eTvixVLB5PecXTl++
|
||
|
"text/plain": [
|
||
|
"<matplotlib.figure.Figure at 0x1fae1b60f98>"
|
||
|
]
|
||
|
},
|
||
|
"metadata": {},
|
||
|
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"FB = fetch_ticker('FB', datetime(2016, 3, 1), datetime(2016, 5, 5))\n",
|
||
|
"ax = ohlc_dataframe(FB)\n",
|
||
|
"plt.vlines(date2num(datetime(2016, 4, 27, 12)),\n",
|
||
|
" ax.get_ylim()[0], ax.get_ylim()[1],\n",
|
||
|
" color='b', label='Earnings Release')\n",
|
||
|
"plt.title('Facebook Price 3/5/2016 - 5/5/2016')\n",
|
||
|
"plt.legend(loc=2);"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"These two charts demonstrate two very specific phonomena: how the market prepares for earnings releases. Let's look at those charts again, but with some extra information. As we're about the see, the market \"knew\" in advance that Apple was going to perform poorly. The market expected that Facebook was going to perform poorly, and instead shot the lights out. Let's see that trend in action:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 4,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAABBEAAAF6CAYAAABP8MBVAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3XmcjfX7x/HXZc++ZUaRUZE2soWIQUVJEam00V7fXyRa\n5Fto07ekfVF20kbRpj1KWixFSrI0iGbabJFtfH5/fM5ojNmdM/c5M+/n4zGP4b7vc9/XbZnzOdf9\n+VyXOecQEREREREREclJsaADEBEREREREZHYoCSCiIiIiIiIiOSKkggiIiIiIiIikitKIoiIiIiI\niIhIriiJICIiIiIiIiK5oiSCiIiIiIiIiOSKkggiRYCZPWNmQwK47mAze66grysiIiLBMLOlZtY2\ngOu+Y2aXFvR1RYoiJRFE8sHMZpvZX2ZWMov9w8xsr5k1z7D9cjPbY2ZbzGyTmS0ysy6hfe3MbF0e\nrv9P6Dy/mdl0M4vL6njn3PXOufvyco+5iGGomU3OZPteMzsydN0RzrlrcnGuT8zsinDGJyIiUlSZ\nWZKZbQ+NE7aGvsebWZ3Q+/SW0NevZvaUmRXP5lx7051jnZk9bGaW1fHOuROcc5+G+X4OGCdkHDc5\n585yzh0wLsnkXPvGKSKSP0oiiOSRmdUB2gB7gXOyOOxS4E/gskz2zXPOVXTOVQbGAa+YWaXQPpfL\nMBxwg3OuIlAfqAw8kkW8kfx/nlm8ub2HsMluMCMiIlIEOaBLaLxRIfQ9Od2+SqExxIlAK+A/OZyr\nYej4jkBv4OqMB2WXiIig/Iw58j1OCegeRaKOkggieXcZ8AUwAeiTcWdoCl880A+4yMxKZHOuccAh\nwFH5iMMAnHObgOnACaHrjzezp83sbTPbCiSGtt2dLsZzzewbM9tsZivM7IzQ9opmNsbMNoSeNtyT\nj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
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"def plot_hilo(ax, start, end, data):\n",
|
||
|
" ax.plot([date2num(start), date2num(end)],\n",
|
||
|
" [data.loc[start]['High'], data.loc[end]['High']],\n",
|
||
|
" color='b')\n",
|
||
|
" ax.plot([date2num(start), date2num(end)],\n",
|
||
|
" [data.loc[start]['Low'], data.loc[end]['Low']],\n",
|
||
|
" color='b')\n",
|
||
|
"\n",
|
||
|
"f, axarr = plt.subplots(1, 2)\n",
|
||
|
"\n",
|
||
|
"ax_aapl = axarr[0]\n",
|
||
|
"ax_fb = axarr[1]\n",
|
||
|
"\n",
|
||
|
"# Plot the AAPL trend up and down\n",
|
||
|
"ohlc_dataframe(AAPL, ax=ax_aapl)\n",
|
||
|
"plot_hilo(ax_aapl, datetime(2016, 3, 1), datetime(2016, 4, 15), AAPL)\n",
|
||
|
"plot_hilo(ax_aapl, datetime(2016, 4, 18), datetime(2016, 4, 26), AAPL)\n",
|
||
|
"ax_aapl.vlines(date2num(datetime(2016, 4, 26, 12)),\n",
|
||
|
" ax_aapl.get_ylim()[0], ax_aapl.get_ylim()[1],\n",
|
||
|
" color='g', label='Earnings Release')\n",
|
||
|
"ax_aapl.legend(loc=2)\n",
|
||
|
"ax_aapl.set_title('AAPL Price History')\n",
|
||
|
"\n",
|
||
|
"# Plot the FB trend down and up\n",
|
||
|
"ohlc_dataframe(FB, ax=ax_fb)\n",
|
||
|
"plot_hilo(ax_fb, datetime(2016, 3, 30), datetime(2016, 4, 27), FB)\n",
|
||
|
"plot_hilo(ax_fb, datetime(2016, 4, 28), datetime(2016, 5, 5), FB)\n",
|
||
|
"ax_fb.vlines(date2num(datetime(2016, 4, 27, 12)),\n",
|
||
|
" ax_fb.get_ylim()[0], ax_fb.get_ylim()[1],\n",
|
||
|
" color='g', label='Earnings Release')\n",
|
||
|
"ax_fb.legend(loc=2)\n",
|
||
|
"ax_fb.set_title('FB Price History')\n",
|
||
|
"\n",
|
||
|
"f.set_size_inches(18, 6)"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"As we can see above, the market broke a prevailing trend on Apple in order to go down, and ultimately predict the earnings release. For Facebook, the opposite happened. While the trend was down, the earnings were fantastic and the market corrected itself much higher."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"# Formulating the Question\n",
|
||
|
"\n",
|
||
|
"While these are two specific examples, there are plenty of other examples you could cite one way or another. Even if the preponderance of evidence shows that the market correctly predicts earnings releases, we need not accuse people of collusion; for a company like Apple with many suppliers we can generally forecast how Apple has done based on those same suppliers.\n",
|
||
|
"\n",
|
||
|
"The question then, is this: **how well does the market predict the earnings releases?** It's an incredibly broad question that I want to disect in a couple of different ways:\n",
|
||
|
"\n",
|
||
|
"1. Given a stock that has been trending down over the past N days before an earnings release, how likely does it continue downward after the release?\n",
|
||
|
"2. Given a stock trending up, how likely does it continue up?\n",
|
||
|
"3. Is there a difference in accuracy between large- and small-cap stocks?\n",
|
||
|
"4. How often, and for how long, do markets trend before an earnings release?\n",
|
||
|
"\n",
|
||
|
"**I want to especially thank Alejandro Saltiel for helping me retrieve the data.** He's great. And now for all of the interesting bits."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"# Event Studies\n",
|
||
|
"\n",
|
||
|
"Before we go too much further, I want to introduce the actual event study. Each chart intends to capture a lot of information and present an easy-to-understand pattern:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 5,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAtEAAAFwCAYAAAB+YSfRAAAABHNCSVQICAgIfA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bd8RjzJo1q9F9FRQU0KNH\nD9xuN9u2beOjjz6qc+zgSHvZd5/R930/TR0L4Ac/+AGrV6/m008/5YwzzjjiMaT9aSRaREREgMAl\n2d544w0Atm/fTs+ePUlISMAYw9y5c+tMGbjssstIT08nLy+PQYMGsXjxYq699to6+9u8eTO33nor\nDoeD8PBwHnvsMRISEpgyZQpZj2axoHQBv/3tb7n44otJTk4mKSmJ8ePHB7c/55xzeOKJJ+jTp0+d\n/aakpDB//vwG24wYMYJ7772X2bNn4/f7CQ8P509/+hODBg3ipJNOoqioiAEDBgSnZTR3jKb2deaZ\nZ/LYY48xcuRIhg8fzqRJkwA46aST+K//+i9OPfVUwsKq49VPWnZ1jqbez1lnndXosQBcLhczZsyg\nR48eugJIiJij+SeV9mSMsZ2lVhERkbYyiw32rq77757eX9v4/X7Gjh3LsmXLOO64447acZrS5b8/\nY7DWNvvbiaZziIiIiHQiW7du5YQTTuD0008PSYCWAE3nEBEREelERowYEbjWtoSURqJFRERERFpJ\nIVpEREREpJUUokVERES6sK1bt+L3+0NdRpejEC0iIiLSBVlrufvuuxk5ciS//OUvQ11Ol6MQLSIi\nItLFVFZWcskll/Db3/4
|
||
|
"text/plain": [
|
||
|
"<matplotlib.figure.Figure at 0x1fae4ffddd8>"
|
||
|
]
|
||
|
},
|
||
|
"metadata": {},
|
||
|
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"import numpy as np\n",
|
||
|
"import pandas as pd\n",
|
||
|
"from pandas.tseries.holiday import USFederalHolidayCalendar\n",
|
||
|
"from pandas.tseries.offsets import CustomBusinessDay\n",
|
||
|
"from datetime import datetime, timedelta\n",
|
||
|
"\n",
|
||
|
"# If you remove rules, it removes them from *all* calendars\n",
|
||
|
"# To ensure we don't pop rules we don't want to, first make\n",
|
||
|
"# sure to fully copy the object\n",
|
||
|
"trade_calendar = USFederalHolidayCalendar()\n",
|
||
|
"trade_calendar.rules.pop(6) # Remove Columbus day\n",
|
||
|
"trade_calendar.rules.pop(7) # Remove Veteran's day\n",
|
||
|
"TradeDay = lambda days: CustomBusinessDay(days, calendar=trade_calendar)\n",
|
||
|
"\n",
|
||
|
"def plot_study(array):\n",
|
||
|
" # Given a 2-d array, we assume the event happens at index `lookback`,\n",
|
||
|
" # and create all of our summary statistics from there.\n",
|
||
|
" lookback = int((array.shape[1] - 1) / 2)\n",
|
||
|
" norm_factor = np.repeat(array[:,lookback].reshape(-1, 1), array.shape[1], axis=1)\n",
|
||
|
" centered_data = array / norm_factor - 1\n",
|
||
|
" lookforward = centered_data.shape[1] - lookback\n",
|
||
|
" means = centered_data.mean(axis=0)\n",
|
||
|
" lookforward_data = centered_data[:,lookforward:]\n",
|
||
|
" std_dev = np.hstack([0, lookforward_data.std(axis=0)])\n",
|
||
|
" maxes = lookforward_data.max(axis=0)\n",
|
||
|
" mins = lookforward_data.min(axis=0)\n",
|
||
|
" \n",
|
||
|
" f, axarr = plt.subplots(1, 2)\n",
|
||
|
" range_begin = -lookback\n",
|
||
|
" range_end = lookforward\n",
|
||
|
" axarr[0].plot(range(range_begin, range_end), means)\n",
|
||
|
" axarr[1].plot(range(range_begin, range_end), means)\n",
|
||
|
" axarr[0].fill_between(range(0, range_end),\n",
|
||
|
" means[-lookforward:] + std_dev,\n",
|
||
|
" means[-lookforward:] - std_dev,\n",
|
||
|
" alpha=.5, label=\"$\\pm$ 1 s.d.\")\n",
|
||
|
" axarr[1].fill_between(range(0, range_end),\n",
|
||
|
" means[-lookforward:] + std_dev,\n",
|
||
|
" means[-lookforward:] - std_dev,\n",
|
||
|
" alpha=.5, label=\"$\\pm$ 1 s.d.\")\n",
|
||
|
" \n",
|
||
|
" max_err = maxes - means[-lookforward+1:]\n",
|
||
|
" min_err = means[-lookforward+1:] - mins\n",
|
||
|
" axarr[0].errorbar(range(1, range_end),\n",
|
||
|
" means[-lookforward+1:],\n",
|
||
|
" yerr=[min_err, max_err], label='Max & Min')\n",
|
||
|
" axarr[0].legend(loc=2)\n",
|
||
|
" axarr[1].legend(loc=2)\n",
|
||
|
" \n",
|
||
|
" axarr[0].set_xlim((-lookback-1, lookback+1))\n",
|
||
|
" axarr[1].set_xlim((-lookback-1, lookback+1))\n",
|
||
|
" \n",
|
||
|
"def plot_study_small(array):\n",
|
||
|
" # Given a 2-d array, we assume the event happens at index `lookback`,\n",
|
||
|
" # and create all of our summary statistics from there.\n",
|
||
|
" lookback = int((array.shape[1] - 1) / 2)\n",
|
||
|
" norm_factor = np.repeat(array[:,lookback].reshape(-1, 1), array.shape[1], axis=1)\n",
|
||
|
" centered_data = array / norm_factor - 1\n",
|
||
|
" lookforward = centered_data.shape[1] - lookback\n",
|
||
|
" means = centered_data.mean(axis=0)\n",
|
||
|
" lookforward_data = centered_data[:,lookforward:]\n",
|
||
|
" std_dev = np.hstack([0, lookforward_data.std(axis=0)])\n",
|
||
|
" maxes = lookforward_data.max(axis=0)\n",
|
||
|
" mins = lookforward_data.min(axis=0)\n",
|
||
|
" \n",
|
||
|
" range_begin = -lookback\n",
|
||
|
" range_end = lookforward\n",
|
||
|
" plt.plot(range(range_begin, range_end), means)\n",
|
||
|
" plt.fill_between(range(0, range_end),\n",
|
||
|
" means[-lookforward:] + std_dev,\n",
|
||
|
" means[-lookforward:] - std_dev,\n",
|
||
|
" alpha=.5, label=\"$\\pm$ 1 s.d.\")\n",
|
||
|
" \n",
|
||
|
" max_err = maxes - means[-lookforward+1:]\n",
|
||
|
" min_err = means[-lookforward+1:] - mins\n",
|
||
|
" plt.errorbar(range(1, range_end),\n",
|
||
|
" means[-lookforward+1:],\n",
|
||
|
" yerr=[min_err, max_err], label='Max & Min')\n",
|
||
|
" plt.legend(loc=2)\n",
|
||
|
" plt.xlim((-lookback-1, lookback+1))\n",
|
||
|
" \n",
|
||
|
"def fetch_event_data(ticker, events, horizon=5):\n",
|
||
|
" # Use horizon+1 to account for including the day of the event,\n",
|
||
|
" # and half-open interval - that is, for a horizon of 5,\n",
|
||
|
" # we should be including 11 events. Additionally, using the\n",
|
||
|
" # CustomBusinessDay means we automatically handle issues if\n",
|
||
|
" # for example a company reports Friday afternoon - the date\n",
|
||
|
" # calculator will turn this into a \"Saturday\" release, but\n",
|
||
|
" # we effectively shift that to Monday with the logic below.\n",
|
||
|
" td_back = TradeDay(horizon+1)\n",
|
||
|
" td_forward = TradeDay(horizon+1)\n",
|
||
|
" \n",
|
||
|
" start_date = min(events) - td_back\n",
|
||
|
" end_date = max(events) + td_forward\n",
|
||
|
" total_data = fetch_ticker(ticker, start_date, end_date)\n",
|
||
|
" event_data = [total_data.ix[event-td_back:event+td_forward]\\\n",
|
||
|
" [0:horizon*2+1]\\\n",
|
||
|
" ['Adjusted Close']\n",
|
||
|
" for event in events]\n",
|
||
|
" return np.array(event_data)\n",
|
||
|
"\n",
|
||
|
"# Generate a couple of random events\n",
|
||
|
"\n",
|
||
|
"event_dates = [datetime(2016, 5, 27) - timedelta(days=1) - TradeDay(x*20) for x in range(1, 40)]\n",
|
||
|
"data = fetch_event_data('CELG', event_dates)\n",
|
||
|
"plot_study_small(data)\n",
|
||
|
"plt.legend(loc=3)\n",
|
||
|
"plt.gcf().set_size_inches(12, 6);\n",
|
||
|
"\n",
|
||
|
"\n",
|
||
|
"plt.annotate('Mean price for days leading up to each event',\n",
|
||
|
" (-5, -.01), (-4.5, .025),\n",
|
||
|
" arrowprops=dict(facecolor='black', shrink=0.05))\n",
|
||
|
"plt.annotate('', (-.1, .005), (-.5, .02),\n",
|
||
|
" arrowprops={'facecolor': 'black', 'shrink': .05})\n",
|
||
|
"plt.annotate('$\\pm$ 1 std. dev. each day', (5, .055), (2.5, .085),\n",
|
||
|
" arrowprops={'facecolor': 'black', 'shrink': .05})\n",
|
||
|
"plt.annotate('Min/Max each day', (.9, -.07), (-1, -.1),\n",
|
||
|
" arrowprops={'facecolor': 'black', 'shrink': .05});"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"And as a quick textual explanation as well:\n",
|
||
|
"\n",
|
||
|
"- The blue line represents the mean price for each day, represented as a percentage of the price on the '0-day'. For example, if we defined an 'event' as whenever the stock price dropped for three days, we would see a decreasing blue line to the left of the 0-day.\n",
|
||
|
"\n",
|
||
|
"- The blue shaded area represents one standard deviation above and below the mean price for each day following an event. This is intended to give us an idea of what the stock price does in general following an event.\n",
|
||
|
"\n",
|
||
|
"- The green bars are the minimum and maximum price for each day following an event. This instructs us as to how much it's possible for the stock to move."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"# Event Type 1: Trending down over the past N days\n",
|
||
|
"\n",
|
||
|
"The first type of event I want to study is how stocks perform when they've been trending down over the past couple of days prior to a release. However, we need to clarify what exactly is meant by \"trending down.\" To do so, we'll use the following metric: **the midpoint between each day's opening and closing price goes down over a period of N days**.\n",
|
||
|
"\n",
|
||
|
"It's probably helpful to have an example:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 6,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAABBEAAAF6CAYAAABP8MBVAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3Xl4VNX5wPHvi6AVZbcQEARcUNSKWBdcG6RV625VqtQF\nrLbaxa3uVUlatS7UWrX0pxbEui+1WjfUWrEiWre6o4IaUTDRsghK6wLn98cdYggJCTDJZPl+nmee\nzJx75p53htG5895z3xMpJSRJkiRJkurSptABSJIkSZKk5sEkgiRJkiRJqheTCJIkSZIkqV5MIkiS\nJEmSpHoxiSBJkiRJkurFJIIkSZIkSaoXkwhSMxYR90fE4bVs6xsRiyNilf87j4hXImKXVd1PPcbJ\nW8ySJKnwIuLMiLh6OdvfiYhd8zDOHyPil6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N+amGD6fu35JUoGllHYtdAyS1Ij6RcTzwMdk9VQmFzogScuXUiotdAyS6rZKSYSI+CXwRUrp\npmrtm5Gtbf+dVdm/JEnSSpgFrJdSmhsRWwF3RcSmKaVPCh2YJEnN3UonESJiJFl11F2rtfcG7iSr\nllq2nOc7tVqSpFqklJyOv5JysyDn5u4/HxFvAQOA56v39XhEkqTa1XQ8Ut8lHivXuAeIiD2AU4F9\nU0qfVWnvBNwLnJ5SeqoeAZFS4lvf+lbl/Ya+jR49ukWN42tqHuOk1Hif86b+70QJjTJOU3//WuJr\nSsnPeb7GUa2WOh6pYVt2J1uvvU3u/vrAhsDbte20MT+/jfF5cozWN4af3aY3jmPU/9ZUP78resza\nUv496nM8UmcSISJuAqY
|
||
|
"text/plain": [
|
||
|
"<matplotlib.figure.Figure at 0x1fae6c517b8>"
|
||
|
]
|
||
|
},
|
||
|
"metadata": {},
|
||
|
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"f, axarr = plt.subplots(1, 2)\n",
|
||
|
"f.set_size_inches(18, 6)\n",
|
||
|
"\n",
|
||
|
"FB_plot = axarr[0]\n",
|
||
|
"ohlc_dataframe(FB[datetime(2016, 4, 18):], FB_plot)\n",
|
||
|
"\n",
|
||
|
"FB_truncated = FB[datetime(2016, 4, 18):datetime(2016, 4, 27)]\n",
|
||
|
"midpoint = FB_truncated['Open']/2 + FB_truncated['Close']/2\n",
|
||
|
"FB_plot.plot(FB_truncated.index, midpoint, label='Midpoint')\n",
|
||
|
"FB_plot.vlines(date2num(datetime(2016, 4, 27, 12)),\n",
|
||
|
" ax_fb.get_ylim()[0], ax_fb.get_ylim()[1],\n",
|
||
|
" color='g', label='Earnings Release')\n",
|
||
|
"FB_plot.legend(loc=2)\n",
|
||
|
"FB_plot.set_title('FB Midpoint Plot')\n",
|
||
|
"\n",
|
||
|
"AAPL_plot = axarr[1]\n",
|
||
|
"ohlc_dataframe(AAPL[datetime(2016, 4, 10):], AAPL_plot)\n",
|
||
|
"AAPL_truncated = AAPL[datetime(2016, 4, 10):datetime(2016, 4, 26)]\n",
|
||
|
"midpoint = AAPL_truncated['Open']/2 + AAPL_truncated['Close']/2\n",
|
||
|
"AAPL_plot.plot(AAPL_truncated.index, midpoint, label='Midpoint')\n",
|
||
|
"AAPL_plot.vlines(date2num(datetime(2016, 4, 26, 12)),\n",
|
||
|
" ax_aapl.get_ylim()[0], ax_aapl.get_ylim()[1],\n",
|
||
|
" color='g', label='Earnings Release')\n",
|
||
|
"AAPL_plot.legend(loc=3)\n",
|
||
|
"AAPL_plot.set_title('AAPL Midpoint Plot');"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Given these charts, we can see that FB was trending down for the four days preceding the earnings release, and AAPL was trending down for a whopping 8 days (we don't count the peak day). This will define the methodology that we will use for the study.\n",
|
||
|
"\n",
|
||
|
"So what are the results? For a given horizon, how well does the market actually perform?"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 7,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"name": "stderr",
|
||
|
"output_type": "stream",
|
||
|
"text": [
|
||
|
"100% (47578 of 47578) |###########################################################| Elapsed Time: 0:21:38 Time: 0:21:38\n"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAABBoAAAGNCAYAAAC/hxIDAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3XmYHVWd//H393Z39qTJBglJOmGXRSDsgoONiiyOgIoK\nqAjjwiig4/xUcEESx1FxXFA2QUHQEZFRUBkWGZXGhC1hSSB0AiHQ2UNCEggBkt7O74+6nXSaTuiQ\nm65e3q/nqedW1T236tu3s9T93HNORUoJSZIkSZKkUijkXYA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z0AVJK6ZqU0h0RcWJEPAO8ApxdivNKkqTeJaXUFBHnAXeTfWFybUppdkScQ/G6ozjh9MPAYKA5\nIr4A7AOMBG4tDo0oB36TUro7n59EkqSeqyRBQ0rpjA60Oa8U59Kmqqur8y6hW/H92jq+X1vH92vr\n+H7pzUop3QXs1Wbf1a3Wn2fTIZst1gIHbt/qeif/Pm8d36+t4/u1dXy/to7v1/YRWzPOojNEROpq\nNUmSlLeIIDkZZKfwWkSSpPZ19Hqky911YnMmTJjA/Pnz8y5Db2D8+PHU1dXlXYYkSSXntUjn8FpC\nkrq/btOjoZic5FCRtoa/J0naPuzR0Hm8FsmX77MkdV0dvR7prNtbSpIkSZKkXsCgQZIkSZIklYxB\ngyRJkiRJKhmDBkmSJEmSVDIGDZIkSZIkqWS6ze0t2/rmNy9lwYIXt9vxq6p24Fvf+rftdvzOcvbZ\nZzNu3Di+9a1v5V2KJEk9jtcjHeP1iCT1Lt02aFiw4EUmTJi03Y5fV7f9jt3iiiuu4Prrr+eJJ57g\njDPO4Lrrrtvu55QkSaX
|
||
|
"text/plain": [
|
||
|
"<matplotlib.figure.Figure at 0x1fae7308128>"
|
||
|
]
|
||
|
},
|
||
|
"metadata": {},
|
||
|
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"# Read in the events for each stock;\n",
|
||
|
"# The file was created using the first code block in the Appendix\n",
|
||
|
"import yaml\n",
|
||
|
"from dateutil.parser import parse\n",
|
||
|
"from progressbar import ProgressBar\n",
|
||
|
"\n",
|
||
|
"data_str = open('earnings_dates.yaml', 'r').read()\n",
|
||
|
"# Need to remove invalid lines\n",
|
||
|
"filtered = filter(lambda x: '{' not in x, data_str.split('\\n'))\n",
|
||
|
"earnings_data = yaml.load('\\n'.join(filtered))\n",
|
||
|
"\n",
|
||
|
"# Convert our earnings data into a list of (ticker, date) pairs\n",
|
||
|
"# to make it easy to work with.\n",
|
||
|
"# This is horribly inefficient, but should get us what we need\n",
|
||
|
"ticker_dates = []\n",
|
||
|
"for ticker, date_list in earnings_data.items():\n",
|
||
|
" for iso_str in date_list:\n",
|
||
|
" ticker_dates.append((ticker, parse(iso_str)))\n",
|
||
|
"\n",
|
||
|
"def does_trend_down(ticker, event, horizon):\n",
|
||
|
" # Figure out if the `event` has a downtrend for\n",
|
||
|
" # the `horizon` days preceding it\n",
|
||
|
" # As an interpretation note: it is assumed that\n",
|
||
|
" # the closing price of day `event` is the reference\n",
|
||
|
" # point, and we want `horizon` days before that.\n",
|
||
|
" # The price_data.hdf was created in the second appendix code block\n",
|
||
|
" try:\n",
|
||
|
" ticker_data = pd.read_hdf('price_data.hdf', ticker)\n",
|
||
|
" data = ticker_data[event-TradeDay(horizon):event]\n",
|
||
|
" midpoints = data['Open']/2 + data['Close']/2\n",
|
||
|
"\n",
|
||
|
" # Shift dates one forward into the future and subtract\n",
|
||
|
" # Effectively: do we trend down over all days?\n",
|
||
|
" elems = midpoints - midpoints.shift(1)\n",
|
||
|
" return len(elems)-1 == len(elems.dropna()[elems <= 0])\n",
|
||
|
" except KeyError:\n",
|
||
|
" # If the stock doesn't exist, it doesn't qualify as trending down\n",
|
||
|
" # Mostly this is here to make sure the entire analysis doesn't \n",
|
||
|
" # blow up if there were issues in data retrieval\n",
|
||
|
" return False\n",
|
||
|
"\n",
|
||
|
"def study_trend(horizon, trend_function):\n",
|
||
|
" five_day_events = np.zeros((1, horizon*2 + 1))\n",
|
||
|
" invalid_events = []\n",
|
||
|
" for ticker, event in ProgressBar()(ticker_dates):\n",
|
||
|
" if trend_function(ticker, event, horizon):\n",
|
||
|
" ticker_data = pd.read_hdf('price_data.hdf', ticker)\n",
|
||
|
" event_data = ticker_data[event-TradeDay(horizon):event+TradeDay(horizon)]['Close']\n",
|
||
|
"\n",
|
||
|
" try:\n",
|
||
|
" five_day_events = np.vstack([five_day_events, event_data])\n",
|
||
|
" except ValueError:\n",
|
||
|
" # Sometimes we don't get exactly the right number of values due to calendar\n",
|
||
|
" # issues. I've fixed most everything I can, and the few issues that are left\n",
|
||
|
" # I assume don't systemically bias the results (i.e. data could be missing\n",
|
||
|
" # because it doesn't exist, etc.). After running through, ~1% of events get\n",
|
||
|
" # discarded this way\n",
|
||
|
" invalid_events.append((ticker, event))\n",
|
||
|
" \n",
|
||
|
"\n",
|
||
|
" # Remove our initial zero row\n",
|
||
|
" five_day_events = five_day_events[1:,:]\n",
|
||
|
" plot_study(five_day_events)\n",
|
||
|
" plt.gcf().suptitle('Action over {} days: {} events'\n",
|
||
|
" .format(horizon,five_day_events.shape[0]))\n",
|
||
|
" plt.gcf().set_size_inches(18, 6)\n",
|
||
|
" \n",
|
||
|
"# Start with a 5 day study\n",
|
||
|
"study_trend(5, does_trend_down)"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"When a stock has been trending down for 5 days, once the earnings are announced it really doesn't move on average. However, the variability is *incredible*. This implies two important things:\n",
|
||
|
"\n",
|
||
|
"1. The market is just as often wrong about an earnings announcement before it happens as it is correct\n",
|
||
|
"2. The incredible width of the min/max bars and standard deviation area tell us that the market reacts *violently* after the earnings are released.\n",
|
||
|
"\n",
|
||
|
"Let's repeat the same study, but over a time horizon of 8 days and 3 days. Presumably if a stock has been going down for 8 days at a time before the earnings, the market should be more accurate."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 8,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"name": "stderr",
|
||
|
"output_type": "stream",
|
||
|
"text": [
|
||
|
"100% (47578 of 47578) |###########################################################| Elapsed Time: 0:20:29 Time: 0:20:29\n"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAABBcAAAGNCAYAAABKeZmzAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/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vizwF8jk/elEulxEOnmfyM+UJgFTHfO/TPynIZcbWEc\ncKiZfQX8ERgd9dgrwCVsG74BPlg4zPwEkAXU/dZ9Z14DluK77c8CZjnn3q5nv1/gr8gwc7vaHwEu\niwwX2I+oHhLOuZX4oOLpqP0vMH/Zy1nAgUQmmNzFnAt3RyZAnI0f9nFd5NjzIj+DecA7wK8j81HU\nXlrzW/yEisVmdls9x70TSIocey7ben8ATMT/O3h5J/sXbLd/tOifzePAXDN7HjgImBp53bdFjici\nIhJ3LPL3WkRERKRBIvM9fAUM1RwDIiIiAuq5ICIiIo1gZifgexU8oGBBREREaqnngoiIiIiIiIg0\niXouiIiIiIiIiEiTKFwQERERERERkSZRuCAiIiIiIiIiTaJwQURERERERESaROGCiIiIiIiIiDSJ\nwgURERERERERaRKFCyIiIiIiIiLSJAoXRERERERERKRJFC6IiIiIiIiISJMoXBARERERERGRJlG4\nICIiIiIiIiJNonBBRERERERERJpE4YKIiIiIiIiINInCBRERERERERFpEoULIiIiIiIiItIkChdE\nREREREREpEkULoiIiIiIiIhIkyhcEBEREREREZEmUbggIiIiIiIiIk0Sk3DBzE41swVmtsjMbqjn\n8Uwze8vMZpvZXDO7LBbnFRERkfjTgHbHxWb2VWT5zMwGN/S5IiIismfMOde0A5iFgEXACUApMA0Y\n6ZxbELXPH4BM59wfzKwrsBDo7pyrbtLJRUREJK40sN1xFDDfOVdmZqcCY51zRzXkuSIiIrJnYtFz\n4QhgsXNumXOuCngJOGu7fRzQMbLeEVitYEFERET2wG7bHc65Kc65ssjdKUDvhj5XRERE9kwswoXe\nwLdR979j2x/xWg8BA82sFPgKuC4G5xUREZH405B2R7QrgHf38LkiIiLSQIktdJ5TgFnOuZ+a2T7A\nv8xssHNu4/Y7mlnTxmmIiIi0U845C7qGtsTMfgKMAY5r5PPUFhEREdmJnbVHYhEulAD9ou73iWyL\nNga4K1LIEjMrBA4Aptd3wKbOAyGxNXbsWMaOHRt0GRIA/e7jl373rY+ZcoWIhrQ7iEzi+DhwqnNu\nbWOeC2qLtEZ6X4pf+t3HL/3uW59dtUdiMSxiGrCvmeWYWTIwEnhru32WASdGiukO7AcsjcG5RURE\nJL7stt1hZv2AicAo59ySxjxXRERE9kyTey4452rM7DfA+/iw4inn3Hwzu8o/7B4H7gSeMbM5kadd\n75xb09Rzi4iISHxpYLvjVqAz8Ij5r1iqnHNH7Oy5Ab0UERGRdiUmcy445yYB+2+37bGo9eX4eRek\nDcrLywu6BAmIfvfxS797ac0a0O64Eriyoc+VtkHvS/FLv/v4pd9922KtbUyhmbnWVpOIiEjQzEwT\nOrYQtUVERETqt6v2SEtdLaLJcnNzWbZsWdBlyG7k5ORQVFQUdBkiIiIxp7ZIy1BbQkSkbWozPRci\nCUkAFUlj6PckItI81HOh5agtEiz9nEVEWq9dtUdicbUIEREREREREYljChdEREREREREpEkULoiI\niIiIiIhIkyhcEBEREREREZEmUbggIiIiIiIiIk3SZi5Fub3bbruf4uJ1zXb8fv2yueOO3zbb8VvK\nmDFj6Nu3L3fccUfQpYiIiLQ7ao80jNojIiLtX5sNF4qL15GbO7bZjl9U1HzHrvXwww/zzDPPMHfu\nXC6++GImTJjQ7OcUERG
|
||
|
"text/plain": [
|
||
|
"<matplotlib.figure.Figure at 0x1fae6c59668>"
|
||
|
]
|
||
|
},
|
||
|
"metadata": {},
|
||
|
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"# 8 day study next\n",
|
||
|
"study_trend(8, does_trend_down)"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"However, looking only at stocks that trended down for 8 days prior to a release, the same pattern emerges: on average, the stock doesn't move, but the market reaction is often incredibly violent."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 9,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"name": "stderr",
|
||
|
"output_type": "stream",
|
||
|
"text": [
|
||
|
"100% (47578 of 47578) |###########################################################| Elapsed Time: 0:26:26 Time: 0:26:26\n"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAABBAAAAGNCAYAAACopYLKAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3Xl8VPW9//HXNwmBsG+yCglK61q3IqK4pGhde9XbuqAo\n1NZbu9rltpVra4FeH636u7e1rXa71aptXVBxRZEqBBAVEEVFRVFBBFzKThDI9v39MQMGCCTAJCeZ\neT0fj3HOnPOdcz5nIsk57/me7wkxRiRJkiRJknYlL+kCJEmSJElS82eAIEmSJEmS6mWAIEmSJEmS\n6mWAIEmSJEmS6mWAIEmSJEmS6mWAIEmSJEmS6mWAIElqsUII54YQakIIn25A21EhhF61Xv85hHBg\n41aYGSGE/iGEuSGEF0IIr4QQrmjAe4pDCK80RX3p7X0nhPB6ur7r0vOODiG8WOtxbq32U0MIC9Lz\nXwghdE/PHxVC+Cg974UQwleaah+2259zWsr/H5IkNZWCpAuQJGkvDAdmABcB4+pp+2VgPvABQIzx\na41a2V4IIeTHGKtrzVoODIkxVoYQ2gKvhhAeijF+UM+qYuNV+YkQQinwb8BnYoxVW8IA4BXgszHG\nmnR481II4eEYY016+UUxxhfrWOXdMcYrG7/yXToXeBRYkHAdkiQ1G/ZAkCS1SCGEdsBQ4KukAoTa\ny64KIbyc/nb7FyGELwGDgL+nv9Vuk/4G/Kh0+4vS7V/e8u15ev76EMK1IYR5IYRnQgj71FFHlxDC\nAyGEl9JtDg0pi0IIHWu1ezOEsE8IoXsI4b4Qwqz049j08jEhhDtCCE8Dd9TeRoyxKsZYmX5ZBISd\nfCafTdf6IvCtWvOLQwjTQwjPpx9D0vNvDyGcXavd30MI/xZCODhd2wvp9e1fz4/jG8B1McaqdL0r\n0s+baoUFRUDNdu/b2XFInfu33b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"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"# 3 day study after that\n",
|
||
|
"study_trend(3, does_trend_down)"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Finally, when we look at a 3-day horizon, we start getting some incredible outliers. Stocks have a potential to move over ~300% up, and the standard deviation width is again, incredible. The results for a 3-day horizon follow the same pattern we've seen in the 5- and 8-day horizons."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"# Event Type 2: Trending up for N days\n",
|
||
|
"\n",
|
||
|
"We're now going to repeat the analysis, but do it for uptrends instead. That is, instead of looking at stocks that have been trending down over the past number of days, we focus only on stocks that have been trending up."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 10,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"name": "stderr",
|
||
|
"output_type": "stream",
|
||
|
"text": [
|
||
|
"100% (47578 of 47578) |###########################################################| Elapsed Time: 0:22:51 Time: 0:22:51\n"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAABBAAAAGNCAYAAACopYLKAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3Xl8FfW9//H352RfIISAiEACIiBCuIAKiBai1rUtWFtv\nUduqV6+9fdRrb3u7aBcBH+391S7Wtrbeayt13+pStXVBLUEWpYhsYZE17AQiCRCWLOd8f3/MSTiE\nhAQ4yZzl9Xw85pEzM9+Z+ZwJy5n3+X5nzDknAAAAAACA4wn4XQAAAAAAAIh9BAgAAAAAAKBNBAgA\nAAAAAKBNBAgAAAAAAKBNBAgAAAAAAKBNBAgAAAAAAKBNBAgAgLh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qe4XAAAklYWSzjKzIjNLl/eZ4nhPdmr6lsTMss0sN/w6\nR9Llkso6slgAAJJRNJ/CAAAAcFKcc0Ezu0PSTHlfcDzinFtlZl/zVruHzayXpA8ldZEUMrNvSjpH\nUk9JL4eHJ6RKeso5N9OfdwIAQOKKaoDgnJstaXY095msSkpK/C4hrnC+Tgzn68Rwvk4M5wsnyzn3\npqQhzZb9X8TrCkn9Wti0RtLIjq0uOfH3+cRwvk4M5+vEcL5ODOerY9iJjHc4pQOZuc46FgAA8cLM\n5LiJYqfh8wgAAMdq7+cR34cw9O/fX5s2bfK7DLShqKhI5eXlfpcBAECH4PNI5+DzBADEN997IIST\njk6pASeP3xMAdAx6IHQuPo/4i/MMALGpvZ9HovEYRwAAAAAAkOAIEAAAAAAAQJsIEAAAAAAAQJsI\nEAAAAAAAQJsIEAAAAAA
|
||
|
"text/plain": [
|
||
|
"<matplotlib.figure.Figure at 0x1fae6e8d438>"
|
||
|
]
|
||
|
},
|
||
|
"metadata": {},
|
||
|
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"def does_trend_up(ticker, event, horizon):\n",
|
||
|
" # Figure out if the `event` has an uptrend for\n",
|
||
|
" # the `horizon` days preceding it\n",
|
||
|
" # As an interpretation note: it is assumed that\n",
|
||
|
" # the closing price of day `event` is the reference\n",
|
||
|
" # point, and we want `horizon` days before that.\n",
|
||
|
" # The price_data.hdf was created in the second appendix code block\n",
|
||
|
" try:\n",
|
||
|
" ticker_data = pd.read_hdf('price_data.hdf', ticker)\n",
|
||
|
" data = ticker_data[event-TradeDay(horizon):event]\n",
|
||
|
" midpoints = data['Open']/2 + data['Close']/2\n",
|
||
|
"\n",
|
||
|
" # Shift dates one forward into the future and subtract\n",
|
||
|
" # Effectively: do we trend down over all days?\n",
|
||
|
" elems = midpoints - midpoints.shift(1)\n",
|
||
|
" return len(elems)-1 == len(elems.dropna()[elems >= 0])\n",
|
||
|
" except KeyError:\n",
|
||
|
" # If the stock doesn't exist, it doesn't qualify as trending down\n",
|
||
|
" # Mostly this is here to make sure the entire analysis doesn't \n",
|
||
|
" # blow up if there were issues in data retrieval\n",
|
||
|
" return False\n",
|
||
|
"\n",
|
||
|
"study_trend(5, does_trend_up)"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"The patterns here are very similar. With the exception of noting that stocks can go to nearly 400% after an earnings announcement (most likely this included a takeover announcement, etc.), we still see large min/max bars and wide standard deviation of returns.\n",
|
||
|
"\n",
|
||
|
"We'll repeat the pattern for stocks going up for both 8 and 3 days straight, but at this point, the results should be very predictable:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 11,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"name": "stderr",
|
||
|
"output_type": "stream",
|
||
|
"text": [
|
||
|
"100% (47578 of 47578) |###########################################################| Elapsed Time: 0:20:51 Time: 0:20:51\n"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAABBcAAAGNCAYAAABKeZmzAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3Xl8nGW9///XZyaTvU1XkjZtlhZFEKpUyqqlLLJ9QUBE\niorQI+rhAXLU4xeKG63Hs+DvezwcF1Q8lE3ZBFQUWpYjKSAUSqGUQte0aZq2SemWNNtkluv3xz1J\nJmnSps0kd5J5P33czr1cc9+fmSntPe+57us25xwiIiIiIiIiIkcq4HcBIiIiIiIiIjK8KVwQERER\nERERkX5RuCAiIiIiIiIi/aJwQURERERERET6ReGCiIiIiIiIiPSLwgURERERERER6ReFCyIiklbM\n7DIzi5vZh/vQ9lozK0pavtvMPjKwFaaOmd1hZqvN7D0zu7MP7UvN7N1Bqu12M6sxs7cS0wWJ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IiIj0i8IF\nEREREREREekXhQsiIiIiIiIi0i8KF0RERERERESkXxQuiIiIiIiIiEi/KFwQERERERERkX5RuCAi\nIiIiIiIi/aJwQURERERERET6ReGCiIiIiIiIiPSLwgURERERERER6ReFCyIiIiIiIiLSLwoXRERE\nRERERKRfFC6IiIiIiIiISL8oXBARERERERGRflG4ICIiIiIiIiL9onBBRERERERERPpF4YKIiIiI\niIiI9IvCBRERERERERHpF4ULIiIiIiIiItIvKQkXzOwCM1trZuvN7NaDtJtlZhEz+2wqjisiIiLp\n51DnHWZ2jJm9amatZvbtw3muiIiIHBlzzvVvB2YBYD1wDrAdWA7Mdc6t7aHd80ALsMg592S/Diwi\nIiJppy/nHWY2ASgFLgP2Oud+2tfnioiIyJFJRc+Fk4ENzrktzrkI8AhwaQ/tvgE8DuxMwTFFREQk\nPR3yvMM5t8s5twKIHu5zRURE5MikIlwoBrYmLdck1nUws8nAZc65XwGWgmOKiIhIejrkeccAPVdE\nREQOImOQjnMnkHxdY68Bg5n17zoNERGREco5p4B+EOhcREREpHe9nY+kIlzYBpQkLU9JrEt2EvCI\nmRkwAbjQzCLOuad6KTYFZUmqLFiwgAULFvhdhvhAn3360mc/9Hj/hAp9O+/o93N1LjL06O+l9KXP\nPn3psx96DnY+kopwYTlwtJmVAjuAucDVyQ2cc9OSirkX+EtvwYKIiIjIQRzyvKOb5LOgw32uiIiI\n9FG/wwXnXMzMbgKewxvD4R7n3Boz+7q32d3d/Sn9PaaIiIikp76cd5hZIfAmMAqIm9k/Acc55xp7\neq5PL0VERGREScmYC865JcAx3db9ppe2/5CKY8rgmTNnjt8liE/02acvffYylB3qvMM5VwdM7etz\nZXjQ30vpS599+tJnP7zYULum0MzcUKtJRETEb2amAR0Hic5FREREenaw85HBultEv5WVlbFlyxa/\ny5BDKC0tpaqqyu8yREREUk7nIoND5xIiIsPTsOm5kEhIfKhIDoc+JxGRgaGeC4NH5yL+0vssIjJ0\nHex8JDDYxYiIiIiIiIjIyKJwQURERERERET6ReGCiIiIiIiIiPSLwgURERERERER6ReFCyIiIiIi\nIiLSL8PmVpTd/fCHd1JdvW/A9l9SMoYf/eibA7b/wTJv3jymTp3Kj370I79LERERGXF0PtI3Oh8R\nERn5hm24UF29j7KyBQO2/6qqgdt3u1/+8pfcd999vPvuu3zhC19g0aJFA35MERERSR2dj4iIyEBw\nzhGNRgmHw7S2thIOhw+Yb2lppakpzP79rTQ2hjnppI9w4okzfKt52IYLQ9kdd9zBrbfeesh2xcXF\n/OAHP+DZZ5+lpaVlECo
|
||
|
"text/plain": [
|
||
|
"<matplotlib.figure.Figure at 0x1fae76e6940>"
|
||
|
]
|
||
|
},
|
||
|
"metadata": {},
|
||
|
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"study_trend(8, does_trend_up)"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 12,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"name": "stderr",
|
||
|
"output_type": "stream",
|
||
|
"text": [
|
||
|
"100% (47578 of 47578) |###########################################################| Elapsed Time: 0:26:56 Time: 0:26:56\n"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAABBAAAAGNCAYAAACopYLKAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3Xl8FfW9//H352SBQEIIawIkAcG64QIuoFaI4kpVXKpC\na11ue+u9j1r7u23v1S4KWO99VB+33lqXtrZ1qbVVVFAUQaQQ9k0EJSyKLGFHCWtYspx8f3/MSTiE\nhBPISeYsr+fjcR6ZM/Od73wmIWTmfb4zY845AQAAAAAAHE/A7wIAAAAAAEDsI0AAAAAAAAARESAA\nAAAAAICICBAAAAAAAEBEBAgAAAAAACAiAgQAAAAAABARAQIAIG6Z2U1mVmNmX2tC27vNLDf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4QWxz4m\nBvYxMbCPSDTOuSmSTqs3749h0zsk5Tewarmk81q2uviRDL837GNiYB8TA/uYXOxErndo1obMXGtt\nCwCAeGFmctxEsdVwPAIAwLGaejzi+yUMvXv3Vmlpqd9lIILCwkJt2LDB7zIAAGgRHI+0Do4nACC+\n+T4CIZR0tEoNOHn8nACgZTACoXVxPOIvvs8AEJuaejwSjcc4AgAAAACABEeAAAAAAAAAIiJAAAAA\nAAAAEREgAAAAAACAiAgQAAAAAABARL4/xrEhjzzyW23cuKfF+i8o6KhHH/1/LdZ/a7j33nuVn5+v\nRx991O9SACCqijcUq3hDcd10Ue8iSVJR76K6aaA1cDwSGccjAJBcYjJA2Lhxj3r3HtNi/W/Y0HJ9\nS9Kzzz6rl156ScuXL9e
|
||
|
"text/plain": [
|
||
|
"<matplotlib.figure.Figure at 0x1fae7851390>"
|
||
|
]
|
||
|
},
|
||
|
"metadata": {},
|
||
|
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"study_trend(3, does_trend_up)"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"# Conclusion and Summary\n",
|
||
|
"\n",
|
||
|
"I guess the most important thing to summarize with is this: **looking at the entire market, stock performance prior to an earnings release has no bearing on the stock's performance.** Honestly: given the huge variability of returns after an earnings release, even when the stock has been trending for a long time, you're best off divesting before an earnings release and letting the market sort itself out.\n",
|
||
|
"\n",
|
||
|
"*However*, there is a big caveat. These results are taken when we look at the entire market. So while we can say that the market as a whole knows nothing and just reacts violently, I want to take a closer look into this data. Does the market typically perform poorly on large-cap/high liquidity stocks? Do smaller companies have investors that know them better and can thus predict performance better? Are specific market sectors better at prediction? Presumably technology stocks are more volatile than the industrials.\n",
|
||
|
"\n",
|
||
|
"So there are some more interesting questions I still want to ask with this data. Knowing that the hard work of data processing is largely already done, it should be fairly simple to continue this analysis and get much more refined with it. Until next time."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"# Appendix\n",
|
||
|
"\n",
|
||
|
"Export event data for Russell 3000 companies:\n",
|
||
|
"\n",
|
||
|
"```python\n",
|
||
|
"import pandas as pd\n",
|
||
|
"from html.parser import HTMLParser\n",
|
||
|
"from datetime import datetime, timedelta\n",
|
||
|
"import requests\n",
|
||
|
"import re\n",
|
||
|
"from dateutil import parser\n",
|
||
|
"import progressbar\n",
|
||
|
"from concurrent import futures\n",
|
||
|
"import yaml\n",
|
||
|
"\n",
|
||
|
"class EarningsParser(HTMLParser):\n",
|
||
|
" store_dates = False\n",
|
||
|
" earnings_offset = None\n",
|
||
|
" dates = []\n",
|
||
|
" \n",
|
||
|
" def __init__(self, *args, **kwargs):\n",
|
||
|
" super().__init__(*args, **kwargs)\n",
|
||
|
" self.dates = []\n",
|
||
|
" \n",
|
||
|
" def handle_starttag(self, tag, attrs):\n",
|
||
|
" if tag == 'table':\n",
|
||
|
" self.store_dates = True\n",
|
||
|
" \n",
|
||
|
" def handle_data(self, data):\n",
|
||
|
" if self.store_dates:\n",
|
||
|
" match = re.match(r'\\d+/\\d+/\\d+', data)\n",
|
||
|
" if match:\n",
|
||
|
" self.dates.append(match.group(0))\n",
|
||
|
" \n",
|
||
|
" # If a company reports before the bell, record the earnings date\n",
|
||
|
" # being at midnight the day before. Ex: WMT reports 5/19/2016,\n",
|
||
|
" # but we want the reference point to be the closing price on 5/18/2016\n",
|
||
|
" if 'After Close' in data:\n",
|
||
|
" self.earnings_offset = timedelta(days=0)\n",
|
||
|
" elif 'Before Open' in data:\n",
|
||
|
" self.earnings_offset = timedelta(days=-1)\n",
|
||
|
" \n",
|
||
|
" def handle_endtag(self, tag):\n",
|
||
|
" if tag == 'table':\n",
|
||
|
" self.store_dates = False\n",
|
||
|
" \n",
|
||
|
"def earnings_releases(ticker):\n",
|
||
|
" #print(\"Looking up ticker {}\".format(ticker))\n",
|
||
|
" user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) '\\\n",
|
||
|
" 'Gecko/20100101 Firefox/46.0'\n",
|
||
|
" headers = {'user-agent': user_agent}\n",
|
||
|
" base_url = 'http://www.streetinsider.com/ec_earnings.php?q={}'\\\n",
|
||
|
" .format(ticker)\n",
|
||
|
" e = EarningsParser()\n",
|
||
|
" s = requests.Session()\n",
|
||
|
" a = requests.adapters.HTTPAdapter(max_retries=0)\n",
|
||
|
" s.mount('http://', a)\n",
|
||
|
" e.feed(str(s.get(base_url, headers=headers).content))\n",
|
||
|
" \n",
|
||
|
" if e.earnings_offset is not None:\n",
|
||
|
" dates = map(lambda x: parser.parse(x) + e.earnings_offset, e.dates)\n",
|
||
|
" past = filter(lambda x: x < datetime.now(), dates)\n",
|
||
|
" return list(map(lambda d: d.isoformat(), past))\n",
|
||
|
"\n",
|
||
|
"# Use a Russell-3000 ETF tracker (ticker IWV) to get a list of holdings\n",
|
||
|
"r3000 = pd.read_csv('https://www.ishares.com/us/products/239714/'\n",
|
||
|
" 'ishares-russell-3000-etf/1449138789749.ajax?'\n",
|
||
|
" 'fileType=csv&fileName=IWV_holdings&dataType=fund',\n",
|
||
|
" header=10)\n",
|
||
|
"r3000_equities = r3000[(r3000['Exchange'] == 'NASDAQ') |\n",
|
||
|
" (r3000['Exchange'] == 'New York Stock Exchange Inc.')]\n",
|
||
|
"\n",
|
||
|
"dates_file = open('earnings_dates.yaml', 'w')\n",
|
||
|
"\n",
|
||
|
"with futures.ThreadPoolExecutor(max_workers=8) as pool:\n",
|
||
|
" fs = {pool.submit(earnings_releases, r3000_equities.ix[t]['Ticker']): t\n",
|
||
|
" for t in r3000_equities.index}\n",
|
||
|
" pbar = progressbar.ProgressBar(term_width=80,\n",
|
||
|
" max_value=r3000_equities.index.max())\n",
|
||
|
" \n",
|
||
|
" for future in futures.as_completed(fs):\n",
|
||
|
" i = fs[future]\n",
|
||
|
" pbar.update(i)\n",
|
||
|
" dates_file.write(yaml.dump({r3000_equities.ix[i]['Ticker']:\n",
|
||
|
" future.result()}))\n",
|
||
|
"```\n",
|
||
|
"\n",
|
||
|
"Downloading stock price data needed for the event studies:\n",
|
||
|
"\n",
|
||
|
"```python\n",
|
||
|
"from secrets import QUANDL_KEY\n",
|
||
|
"import pandas as pd\n",
|
||
|
"import yaml\n",
|
||
|
"from dateutil.parser import parse\n",
|
||
|
"from datetime import timedelta\n",
|
||
|
"import quandl\n",
|
||
|
"from progressbar import ProgressBar\n",
|
||
|
"\n",
|
||
|
"def fetch_ticker(ticker, start, end):\n",
|
||
|
" # Quandl is currently giving me issues with returning\n",
|
||
|
" # the entire dataset and not slicing server-side.\n",
|
||
|
" # So instead, we'll do it client-side!\n",
|
||
|
" q_format = '%Y-%m-%d'\n",
|
||
|
" ticker_data = quandl.get('YAHOO/' + ticker,\n",
|
||
|
" start_date=start.strftime(q_format),\n",
|
||
|
" end_date=end.strftime(q_format),\n",
|
||
|
" authtoken=QUANDL_KEY)\n",
|
||
|
" return ticker_data\n",
|
||
|
" \n",
|
||
|
"data_str = open('earnings_dates.yaml', 'r').read()\n",
|
||
|
"# Need to remove invalid lines\n",
|
||
|
"filtered = filter(lambda x: '{' not in x, data_str.split('\\n'))\n",
|
||
|
"earnings_data = yaml.load('\\n'.join(filtered))\n",
|
||
|
"\n",
|
||
|
"# Get the first 1500 keys - split up into two statements\n",
|
||
|
"# because of Quandl rate limits\n",
|
||
|
"tickers = list(earnings_data.keys())\n",
|
||
|
"\n",
|
||
|
"price_dict = {}\n",
|
||
|
"invalid_tickers = []\n",
|
||
|
"for ticker in ProgressBar()(tickers[0:1500]):\n",
|
||
|
" try:\n",
|
||
|
" # Replace '.' with '-' in name for some tickers\n",
|
||
|
" fixed = ticker.replace('.', '-')\n",
|
||
|
" event_strs = earnings_data[ticker]\n",
|
||
|
" events = [parse(event) for event in event_strs]\n",
|
||
|
" td = timedelta(days=20)\n",
|
||
|
" price_dict[ticker] = fetch_ticker(fixed,\n",
|
||
|
" min(events)-td, max(events)+td)\n",
|
||
|
" except quandl.NotFoundError:\n",
|
||
|
" invalid_tickers.append(ticker)\n",
|
||
|
" \n",
|
||
|
"# Execute this after 10 minutes have passed\n",
|
||
|
"for ticker in ProgressBar()(tickers[1500:]):\n",
|
||
|
" try:\n",
|
||
|
" # Replace '.' with '-' in name for some tickers\n",
|
||
|
" fixed = ticker.replace('.', '-')\n",
|
||
|
" event_strs = earnings_data[ticker]\n",
|
||
|
" events = [parse(event) for event in event_strs]\n",
|
||
|
" td = timedelta(days=20)\n",
|
||
|
" price_dict[ticker] = fetch_ticker(fixed,\n",
|
||
|
" min(events)-td, max(events)+td)\n",
|
||
|
" except quandl.NotFoundError:\n",
|
||
|
" invalid_tickers.append(ticker)\n",
|
||
|
" \n",
|
||
|
"prices_store = pd.HDFStore('price_data.hdf')\n",
|
||
|
"for ticker, prices in price_dict.items():\n",
|
||
|
" prices_store[ticker] = prices\n",
|
||
|
"```"
|
||
|
]
|
||
|
}
|
||
|
],
|
||
|
"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.4.3"
|
||
|
}
|
||
|
},
|
||
|
"nbformat": 4,
|
||
|
"nbformat_minor": 0
|
||
|
}
|