ml-finance-python
python scripts for finance machine learning
git clone https://9o.is/git/ml-finance-python.git
notebook.ipynb
(10115B)
1 {
2 "cells": [
3 {
4 "cell_type": "markdown",
5 "metadata": {
6 "deletable": true,
7 "editable": true
8 },
9 "source": [
10 "# Exercises: Variance - Answer Key\n",
11 "By Christopher van Hoecke, Maxwell Margenot, and Delaney Mackenzie\n",
12 "\n",
13 "## Lecture Link :\n",
14 "https://www.quantopian.com/lectures/variance\n",
15 "\n",
16 "### IMPORTANT NOTE: \n",
17 "This lecture corresponds to the Variance lecture, which is part of the Quantopian lecture series. This homework expects you to rely heavily on the code presented in the corresponding lecture. Please copy and paste regularly from that lecture when starting to work on the problems, as trying to do them from scratch will likely be too difficult.\n",
18 "\n",
19 "Part of the Quantopian Lecture Series:\n",
20 "\n",
21 "* [www.quantopian.com/lectures](https://www.quantopian.com/lectures)\n",
22 "* [github.com/quantopian/research_public](https://github.com/quantopian/research_public)\n",
23 "\n",
24 "----"
25 ]
26 },
27 {
28 "cell_type": "code",
29 "execution_count": 1,
30 "metadata": {
31 "collapsed": true,
32 "deletable": true,
33 "editable": true
34 },
35 "outputs": [],
36 "source": [
37 "# Useful Libraries\n",
38 "import pandas as pd\n",
39 "import numpy as np\n",
40 "import matplotlib.pyplot as plt"
41 ]
42 },
43 {
44 "cell_type": "markdown",
45 "metadata": {
46 "deletable": true,
47 "editable": true
48 },
49 "source": [
50 "#### Data: "
51 ]
52 },
53 {
54 "cell_type": "code",
55 "execution_count": 2,
56 "metadata": {
57 "collapsed": true,
58 "deletable": true,
59 "editable": true
60 },
61 "outputs": [],
62 "source": [
63 "X = np.random.randint(100, size = 100)"
64 ]
65 },
66 {
67 "cell_type": "markdown",
68 "metadata": {
69 "deletable": true,
70 "editable": true
71 },
72 "source": [
73 "---"
74 ]
75 },
76 {
77 "cell_type": "markdown",
78 "metadata": {
79 "deletable": true,
80 "editable": true
81 },
82 "source": [
83 "# Exercise 1: \n",
84 "Using the skills aquired in the lecture series, find the following parameters of the list X above:\n",
85 "- Range\n",
86 "- Mean Absolute Deviation\n",
87 "- Variance and Standard Deviation\n",
88 "- Semivariance and Semideviation\n",
89 "- Target variance (with B = 60)"
90 ]
91 },
92 {
93 "cell_type": "code",
94 "execution_count": 3,
95 "metadata": {
96 "collapsed": false,
97 "deletable": true,
98 "editable": true
99 },
100 "outputs": [
101 {
102 "name": "stdout",
103 "output_type": "stream",
104 "text": [
105 "Range of X: 99\n"
106 ]
107 }
108 ],
109 "source": [
110 "# Range of X\n",
111 "\n",
112 "print 'Range of X: %s' %(np.ptp(X))"
113 ]
114 },
115 {
116 "cell_type": "code",
117 "execution_count": 4,
118 "metadata": {
119 "collapsed": false,
120 "deletable": true,
121 "editable": true
122 },
123 "outputs": [
124 {
125 "name": "stdout",
126 "output_type": "stream",
127 "text": [
128 "Mean absolute deviation of X: 24.6858\n"
129 ]
130 }
131 ],
132 "source": [
133 "# Mean Absolute Deviation\n",
134 "# First calculate the value of mu (the mean)\n",
135 "\n",
136 "mu = np.mean(X)\n",
137 "\n",
138 "abs_dispersion = [np.abs(mu - x) for x in X]\n",
139 "MAD = np.sum(abs_dispersion)/len(abs_dispersion)\n",
140 "\n",
141 "print 'Mean absolute deviation of X:', MAD"
142 ]
143 },
144 {
145 "cell_type": "code",
146 "execution_count": 5,
147 "metadata": {
148 "collapsed": false,
149 "deletable": true,
150 "editable": true
151 },
152 "outputs": [
153 {
154 "name": "stdout",
155 "output_type": "stream",
156 "text": [
157 "Variance of X: 817.7859\n",
158 "Standard deviation of X: 28.5969561317\n"
159 ]
160 }
161 ],
162 "source": [
163 "# Variance and standard deviation\n",
164 "\n",
165 "print 'Variance of X:', np.var(X)\n",
166 "print 'Standard deviation of X:', np.std(X)"
167 ]
168 },
169 {
170 "cell_type": "code",
171 "execution_count": 6,
172 "metadata": {
173 "collapsed": false,
174 "deletable": true,
175 "editable": true
176 },
177 "outputs": [
178 {
179 "name": "stdout",
180 "output_type": "stream",
181 "text": [
182 "Semivariance of X: 804.51664902\n",
183 "Semideviation of X: 28.3640026974\n"
184 ]
185 }
186 ],
187 "source": [
188 "# Semivariance and semideviation\n",
189 "\n",
190 "lows = [e for e in X if e <= mu]\n",
191 "\n",
192 "semivar = np.sum( (lows - mu) ** 2 ) / len(lows)\n",
193 "\n",
194 "print 'Semivariance of X:', semivar\n",
195 "print 'Semideviation of X:', np.sqrt(semivar)"
196 ]
197 },
198 {
199 "cell_type": "code",
200 "execution_count": 7,
201 "metadata": {
202 "collapsed": false,
203 "deletable": true,
204 "editable": true,
205 "scrolled": true
206 },
207 "outputs": [
208 {
209 "name": "stdout",
210 "output_type": "stream",
211 "text": [
212 "Target semivariance of X: 1182\n",
213 "Target semideviation of X: 34.3802268753\n"
214 ]
215 }
216 ],
217 "source": [
218 "# Target variance\n",
219 "\n",
220 "B = 60\n",
221 "lows_B = [e for e in X if e <= B]\n",
222 "semivar_B = sum(map(lambda x: (x - B)**2,lows_B))/len(lows_B)\n",
223 "\n",
224 "print 'Target semivariance of X:', semivar_B\n",
225 "print 'Target semideviation of X:', np.sqrt(semivar_B)"
226 ]
227 },
228 {
229 "cell_type": "markdown",
230 "metadata": {
231 "deletable": true,
232 "editable": true
233 },
234 "source": [
235 "----"
236 ]
237 },
238 {
239 "cell_type": "markdown",
240 "metadata": {
241 "deletable": true,
242 "editable": true
243 },
244 "source": [
245 "# Exercise 2:\n",
246 "Using the skills aquired in the lecture series, find the following parameters of prices for AT&T stock over a year:\n",
247 "- 30 days rolling variance \n",
248 "- 15 days rolling Standard Deviation"
249 ]
250 },
251 {
252 "cell_type": "code",
253 "execution_count": 8,
254 "metadata": {
255 "collapsed": false,
256 "deletable": true,
257 "editable": true
258 },
259 "outputs": [],
260 "source": [
261 "att = get_pricing('T', fields='open_price', start_date='2016-01-01', end_date='2017-01-01')"
262 ]
263 },
264 {
265 "cell_type": "code",
266 "execution_count": 9,
267 "metadata": {
268 "collapsed": false,
269 "deletable": true,
270 "editable": true
271 },
272 "outputs": [],
273 "source": [
274 "# Rolling mean\n",
275 "variance = att.rolling(window = 30).var()"
276 ]
277 },
278 {
279 "cell_type": "code",
280 "execution_count": 10,
281 "metadata": {
282 "collapsed": false,
283 "deletable": true,
284 "editable": true,
285 "scrolled": true
286 },
287 "outputs": [],
288 "source": [
289 "# Rolling standard deviation\n",
290 "std = att.rolling(window = 15).std()"
291 ]
292 },
293 {
294 "cell_type": "markdown",
295 "metadata": {
296 "deletable": true,
297 "editable": true
298 },
299 "source": [
300 "----"
301 ]
302 },
303 {
304 "cell_type": "markdown",
305 "metadata": {
306 "deletable": true,
307 "editable": true
308 },
309 "source": [
310 "# Exercise 3 : \n",
311 "The portfolio variance is calculated as\n",
312 "\n",
313 "$$\\text{VAR}_p = \\text{VAR}_{s1} (w_1^2) + \\text{VAR}_{s2}(w_2^2) + \\text{COV}_{S_1, S_2} (2 w_1 w_2)$$\n",
314 "\n",
315 "Where $w_1$ and $w_2$ are the weights of $S_1$ and $S_2$.\n",
316 "\n",
317 "Find values of $w_1$ and $w_2$ to have a portfolio variance of 50. "
318 ]
319 },
320 {
321 "cell_type": "code",
322 "execution_count": 11,
323 "metadata": {
324 "collapsed": false,
325 "deletable": true,
326 "editable": true
327 },
328 "outputs": [
329 {
330 "name": "stdout",
331 "output_type": "stream",
332 "text": [
333 "Portfolio variance: 50.1862438743\n"
334 ]
335 }
336 ],
337 "source": [
338 "asset1 = get_pricing('AAPL', fields='open_price', start_date='2016-01-01', end_date='2017-01-01')\n",
339 "asset2 = get_pricing('XLF', fields='open_price', start_date='2016-01-01', end_date='2017-01-01')\n",
340 "\n",
341 "cov = np.cov(asset1, asset2)[0,1]\n",
342 "\n",
343 "w1 = 0.87\n",
344 "w2 = 1 - w1\n",
345 "\n",
346 "v1 = np.var(asset1)\n",
347 "v2 = np.var(asset2)\n",
348 "\n",
349 "pvariance = (w1**2)*v1+(w2**2)*v2+(2*w1*w2)*cov\n",
350 "\n",
351 "print 'Portfolio variance: ', pvariance"
352 ]
353 },
354 {
355 "cell_type": "markdown",
356 "metadata": {
357 "deletable": true,
358 "editable": true
359 },
360 "source": [
361 "---\n",
362 "\n",
363 "Congratulations on completing the Variance answer key!\n",
364 "\n",
365 "As you learn more about writing trading models and the Quantopian platform, enter a daily [Quantopian Contest](https://www.quantopian.com/contest). Your strategy will be evaluated for a cash prize every day.\n",
366 "\n",
367 "Start by going through the [Writing a Contest Algorithm](https://www.quantopian.com/tutorials/contest) tutorial."
368 ]
369 },
370 {
371 "cell_type": "markdown",
372 "metadata": {
373 "deletable": true,
374 "editable": true
375 },
376 "source": [
377 "*This presentation is for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation for any security; nor does it constitute an offer to provide investment advisory or other services by Quantopian, Inc. (\"Quantopian\"). Nothing contained herein constitutes investment advice or offers any opinion with respect to the suitability of any security, and any views expressed herein should not be taken as advice to buy, sell, or hold any security or as an endorsement of any security or company. In preparing the information contained herein, Quantopian, Inc. has not taken into account the investment needs, objectives, and financial circumstances of any particular investor. Any views expressed and data illustrated herein were prepared based upon information, believed to be reliable, available to Quantopian, Inc. at the time of publication. Quantopian makes no guarantees as to their accuracy or completeness. All information is subject to change and may quickly become unreliable for various reasons, including changes in market conditions or economic circumstances.*"
378 ]
379 }
380 ],
381 "metadata": {
382 "kernelspec": {
383 "display_name": "Python 2",
384 "language": "python",
385 "name": "python2"
386 },
387 "language_info": {
388 "codemirror_mode": {
389 "name": "ipython",
390 "version": 2
391 },
392 "file_extension": ".py",
393 "mimetype": "text/x-python",
394 "name": "python",
395 "nbconvert_exporter": "python",
396 "pygments_lexer": "ipython2",
397 "version": "2.7.12"
398 }
399 },
400 "nbformat": 4,
401 "nbformat_minor": 2
402 }