ml-finance-python
python scripts for finance machine learning
git clone https://9o.is/git/ml-finance-python.git
01_preprocessing.ipynb
(16994B)
1 {
2 "cells": [
3 {
4 "cell_type": "markdown",
5 "metadata": {
6 "slideshow": {
7 "slide_type": "slide"
8 }
9 },
10 "source": [
11 "## Imports"
12 ]
13 },
14 {
15 "cell_type": "code",
16 "execution_count": 2,
17 "metadata": {
18 "ExecuteTime": {
19 "end_time": "2018-12-06T23:48:01.991368Z",
20 "start_time": "2018-12-06T23:48:01.225480Z"
21 },
22 "slideshow": {
23 "slide_type": "fragment"
24 }
25 },
26 "outputs": [],
27 "source": [
28 "import os, tarfile, sys\n",
29 "from pathlib import Path\n",
30 "from time import time\n",
31 "from pprint import pprint\n",
32 "from collections import Counter\n",
33 "\n",
34 "import numpy as np\n",
35 "from numpy.random import choice\n",
36 "import pandas as pd\n",
37 "\n",
38 "import spacy\n",
39 "\n",
40 "from gensim.models.word2vec import LineSentence\n",
41 "from gensim.models.phrases import Phrases, Phraser"
42 ]
43 },
44 {
45 "cell_type": "markdown",
46 "metadata": {
47 "slideshow": {
48 "slide_type": "slide"
49 }
50 },
51 "source": [
52 "### Settings"
53 ]
54 },
55 {
56 "cell_type": "code",
57 "execution_count": 3,
58 "metadata": {
59 "ExecuteTime": {
60 "end_time": "2018-12-06T23:48:03.594481Z",
61 "start_time": "2018-12-06T23:48:03.586268Z"
62 },
63 "slideshow": {
64 "slide_type": "fragment"
65 }
66 },
67 "outputs": [],
68 "source": [
69 "pd.set_option('float_format', '{:,.2f}'.format)\n",
70 "np.random.seed(42)"
71 ]
72 },
73 {
74 "cell_type": "code",
75 "execution_count": 4,
76 "metadata": {
77 "ExecuteTime": {
78 "end_time": "2018-12-06T23:48:05.233653Z",
79 "start_time": "2018-12-06T23:48:05.231815Z"
80 },
81 "slideshow": {
82 "slide_type": "fragment"
83 }
84 },
85 "outputs": [],
86 "source": [
87 "LANGUAGES = ['en', 'es']\n",
88 "language_dict = dict(zip(LANGUAGES, ['English', 'Spanish']))"
89 ]
90 },
91 {
92 "cell_type": "code",
93 "execution_count": 5,
94 "metadata": {
95 "ExecuteTime": {
96 "end_time": "2018-12-06T23:48:06.189629Z",
97 "start_time": "2018-12-06T23:48:06.187637Z"
98 },
99 "slideshow": {
100 "slide_type": "fragment"
101 }
102 },
103 "outputs": [],
104 "source": [
105 "def format_time(t):\n",
106 " m, s = divmod(t, 60)\n",
107 " h, m = divmod(m, 60)\n",
108 " return '{:02.0f}:{:02.0f}:{:02.0f}'.format(h, m, s)"
109 ]
110 },
111 {
112 "cell_type": "markdown",
113 "metadata": {
114 "slideshow": {
115 "slide_type": "slide"
116 }
117 },
118 "source": [
119 "## Preprocess Data"
120 ]
121 },
122 {
123 "cell_type": "markdown",
124 "metadata": {
125 "slideshow": {
126 "slide_type": "fragment"
127 }
128 },
129 "source": [
130 "### TED 2013 English & Spanish"
131 ]
132 },
133 {
134 "cell_type": "code",
135 "execution_count": 6,
136 "metadata": {
137 "ExecuteTime": {
138 "end_time": "2018-12-06T23:48:18.238647Z",
139 "start_time": "2018-12-06T23:48:18.236727Z"
140 },
141 "slideshow": {
142 "slide_type": "fragment"
143 }
144 },
145 "outputs": [],
146 "source": [
147 "SOURCE = 'TED'\n",
148 "FILE_NAME = 'TED2013'\n",
149 "DATA_DIR = Path('..', 'data')"
150 ]
151 },
152 {
153 "cell_type": "markdown",
154 "metadata": {
155 "slideshow": {
156 "slide_type": "fragment"
157 }
158 },
159 "source": [
160 "Data source: http://opus.nlpl.eu/TED2013.php"
161 ]
162 },
163 {
164 "cell_type": "code",
165 "execution_count": 7,
166 "metadata": {
167 "ExecuteTime": {
168 "end_time": "2018-12-06T23:48:22.643258Z",
169 "start_time": "2018-12-06T23:48:22.621225Z"
170 },
171 "slideshow": {
172 "slide_type": "fragment"
173 }
174 },
175 "outputs": [
176 {
177 "name": "stdout",
178 "output_type": "stream",
179 "text": [
180 "http://www.ted.com/talks/stephen_palumbi_following_the_mercury_trail.html\n",
181 "There's a tight and surprising link between the ocean's health and ours, says marine biologist Stephen Palumbi. He shows how toxins at the bottom of the ocean food chain find their way into our bodies, with a shocking story of toxic contamination from a Japanese fish market. His work points a way forward for saving the oceans' health -- and humanity's.\n",
182 "fish,health,mission blue,oceans,science\n",
183 "899\n",
184 "Stephen Palumbi: Following \n"
185 ]
186 }
187 ],
188 "source": [
189 "filename = DATA_DIR / 'TED' / 'TED2013.en'\n",
190 "print(filename.read_text()[:500])"
191 ]
192 },
193 {
194 "cell_type": "markdown",
195 "metadata": {
196 "slideshow": {
197 "slide_type": "slide"
198 }
199 },
200 "source": [
201 "### Tokenize & Clean Sentences\n",
202 "\n",
203 "Models expect data provided as a single sentence per line. We'll remove punctuation after using `spaCy`'s parser to tokenize the input text."
204 ]
205 },
206 {
207 "cell_type": "code",
208 "execution_count": 8,
209 "metadata": {
210 "ExecuteTime": {
211 "end_time": "2018-12-06T23:50:07.184530Z",
212 "start_time": "2018-12-06T23:50:07.180561Z"
213 },
214 "slideshow": {
215 "slide_type": "fragment"
216 }
217 },
218 "outputs": [],
219 "source": [
220 "def read_sentences(path, min_sent_length=3):\n",
221 " stats = pd.DataFrame()\n",
222 " sentences = []\n",
223 " skipped, word_count = 0, 0\n",
224 " \n",
225 " with path.open() as source:\n",
226 " for sentence in source:\n",
227 " # remove short sentences and urls (for TED data)\n",
228 " n_words = len(sentence.split())\n",
229 " if n_words < min_sent_length or sentence.startswith('http:///'):\n",
230 " skipped += 1\n",
231 " else:\n",
232 " word_count += n_words\n",
233 " sentences.append(sentence.strip())\n",
234 " \n",
235 " stats = pd.Series({'Sentences': len(sentences),\n",
236 " '# Words': word_count,\n",
237 " 'Skipped': skipped})\n",
238 " return sentences, stats"
239 ]
240 },
241 {
242 "cell_type": "code",
243 "execution_count": 9,
244 "metadata": {
245 "ExecuteTime": {
246 "end_time": "2018-12-06T23:50:09.575500Z",
247 "start_time": "2018-12-06T23:50:09.571893Z"
248 },
249 "run_control": {
250 "marked": false
251 },
252 "slideshow": {
253 "slide_type": "slide"
254 }
255 },
256 "outputs": [],
257 "source": [
258 "def clean_sentences(sents, nlp, path, lang):\n",
259 " exclude = ['PUNCT', 'SYM', 'X']\n",
260 " start = time()\n",
261 " vocab = Counter()\n",
262 " sents = nlp.pipe(sents)\n",
263 " d = []\n",
264 " with open(path / 'ngrams_1.txt'.format(language), 'a') as f:\n",
265 " for i, sent in enumerate(sents):\n",
266 " if i % 20000 == 0 and i > 0:\n",
267 " print(i, end=' ')\n",
268 " d.extend([[i, w.text, w.pos_] for w in sent])\n",
269 " clean_sentence = [w.text.lower() for w in sent if w.pos_ not in exclude]\n",
270 " vocab.update(clean_sentence)\n",
271 " f.write(' '.join(clean_sentence) + '\\n')\n",
272 "\n",
273 " vocab = pd.Series(vocab).sort_values(ascending=False).to_frame('count')\n",
274 " with pd.HDFStore(path.parent / 'vocab.h5') as store:\n",
275 " store.put('/'.join([lang, 'vocab']), vocab)\n",
276 " store.put('/'.join([lang, 'tokens']), pd.DataFrame(d, columns=['sent_id', 'token', 'pos']))\n",
277 " duration = time() - start\n",
278 " print('\\n\\tDuration: ', format_time(duration))"
279 ]
280 },
281 {
282 "cell_type": "code",
283 "execution_count": 12,
284 "metadata": {
285 "ExecuteTime": {
286 "end_time": "2018-12-07T00:04:12.266702Z",
287 "start_time": "2018-12-06T23:50:10.355827Z"
288 },
289 "scrolled": true,
290 "slideshow": {
291 "slide_type": "slide"
292 }
293 },
294 "outputs": [
295 {
296 "name": "stdout",
297 "output_type": "stream",
298 "text": [
299 "en: 20000 40000 60000 80000 100000 120000 140000 \n",
300 "\tDuration: 00:07:01\n",
301 "es: 20000 40000 60000 80000 100000 120000 140000 \n",
302 "\tDuration: 00:06:49\n"
303 ]
304 }
305 ],
306 "source": [
307 "sentences, stats = {}, pd.DataFrame()\n",
308 "\n",
309 "for language in LANGUAGES:\n",
310 " source_path = DATA_DIR / SOURCE / '{}.{}'.format(FILE_NAME, language)\n",
311 " sentences[language], stats[language_dict[language]] = read_sentences(source_path)\n",
312 " \n",
313 " print(language, end=': ')\n",
314 " target_path = Path('vocab', SOURCE, language)\n",
315 " if not target_path.exists():\n",
316 " target_path.mkdir(parents=True, exist_ok=True)\n",
317 "\n",
318 " clean_sentences(sentences[language], spacy.load(language), target_path, language) "
319 ]
320 },
321 {
322 "cell_type": "markdown",
323 "metadata": {
324 "slideshow": {
325 "slide_type": "slide"
326 }
327 },
328 "source": [
329 "### Corpus Summary Stats"
330 ]
331 },
332 {
333 "cell_type": "code",
334 "execution_count": 14,
335 "metadata": {
336 "ExecuteTime": {
337 "end_time": "2018-12-07T00:07:34.749099Z",
338 "start_time": "2018-12-07T00:07:34.741418Z"
339 },
340 "scrolled": true,
341 "slideshow": {
342 "slide_type": "fragment"
343 }
344 },
345 "outputs": [
346 {
347 "data": {
348 "text/html": [
349 "<div>\n",
350 "<style scoped>\n",
351 " .dataframe tbody tr th:only-of-type {\n",
352 " vertical-align: middle;\n",
353 " }\n",
354 "\n",
355 " .dataframe tbody tr th {\n",
356 " vertical-align: top;\n",
357 " }\n",
358 "\n",
359 " .dataframe thead th {\n",
360 " text-align: right;\n",
361 " }\n",
362 "</style>\n",
363 "<table border=\"1\" class=\"dataframe\">\n",
364 " <thead>\n",
365 " <tr style=\"text-align: right;\">\n",
366 " <th></th>\n",
367 " <th>English</th>\n",
368 " <th>Spanish</th>\n",
369 " </tr>\n",
370 " </thead>\n",
371 " <tbody>\n",
372 " <tr>\n",
373 " <th># Words</th>\n",
374 " <td>2,640,928</td>\n",
375 " <td>2,548,942</td>\n",
376 " </tr>\n",
377 " <tr>\n",
378 " <th>Sentences</th>\n",
379 " <td>152,729</td>\n",
380 " <td>151,850</td>\n",
381 " </tr>\n",
382 " <tr>\n",
383 " <th>Skipped</th>\n",
384 " <td>5,166</td>\n",
385 " <td>6,045</td>\n",
386 " </tr>\n",
387 " </tbody>\n",
388 "</table>\n",
389 "</div>"
390 ],
391 "text/plain": [
392 " English Spanish\n",
393 "# Words 2,640,928 2,548,942\n",
394 "Sentences 152,729 151,850\n",
395 "Skipped 5,166 6,045"
396 ]
397 },
398 "execution_count": 14,
399 "metadata": {},
400 "output_type": "execute_result"
401 }
402 ],
403 "source": [
404 "stats.applymap(lambda x: '{:,d}'.format(x))"
405 ]
406 },
407 {
408 "cell_type": "code",
409 "execution_count": 15,
410 "metadata": {
411 "ExecuteTime": {
412 "end_time": "2018-12-07T00:07:37.530218Z",
413 "start_time": "2018-12-07T00:07:37.523597Z"
414 },
415 "slideshow": {
416 "slide_type": "fragment"
417 }
418 },
419 "outputs": [],
420 "source": [
421 "with pd.HDFStore(Path('vocab', SOURCE, 'vocab.h5')) as store:\n",
422 " store.put('stats', stats)"
423 ]
424 },
425 {
426 "cell_type": "markdown",
427 "metadata": {
428 "slideshow": {
429 "slide_type": "slide"
430 }
431 },
432 "source": [
433 "### Inspect Result"
434 ]
435 },
436 {
437 "cell_type": "code",
438 "execution_count": 16,
439 "metadata": {
440 "ExecuteTime": {
441 "end_time": "2018-12-07T00:07:40.045413Z",
442 "start_time": "2018-12-07T00:07:40.040404Z"
443 },
444 "slideshow": {
445 "slide_type": "fragment"
446 }
447 },
448 "outputs": [
449 {
450 "data": {
451 "text/plain": [
452 "[\"There's a tight and surprising link between the ocean's health and ours, says marine biologist Stephen Palumbi. He shows how toxins at the bottom of the ocean food chain find their way into our bodies, with a shocking story of toxic contamination from a Japanese fish market. His work points a way forward for saving the oceans' health -- and humanity's.\",\n",
453 " 'Stephen Palumbi: Following the mercury trail',\n",
454 " 'It can be a very complicated thing, the ocean.']"
455 ]
456 },
457 "execution_count": 16,
458 "metadata": {},
459 "output_type": "execute_result"
460 }
461 ],
462 "source": [
463 "sentences['en'][:3]"
464 ]
465 },
466 {
467 "cell_type": "code",
468 "execution_count": 17,
469 "metadata": {
470 "ExecuteTime": {
471 "end_time": "2018-12-07T00:07:40.972554Z",
472 "start_time": "2018-12-07T00:07:40.970041Z"
473 },
474 "slideshow": {
475 "slide_type": "fragment"
476 }
477 },
478 "outputs": [
479 {
480 "data": {
481 "text/plain": [
482 "['Existe una estrecha y sorprendente relación entre nuestra salud y la salud del océano, dice el biologo marino Stephen Palumbi. Nos muestra, através de una impactante historia acerca de la contaminación tóxica en el mercado pesquero japonés, como las toxinas de la cadena alimenticia del fondo oceánico llegan a nuestro cuerpo.',\n",
483 " 'Stephen Palumbi: Siguiendo el camino del mercurio.',\n",
484 " 'El océano puede ser una cosa muy complicada.']"
485 ]
486 },
487 "execution_count": 17,
488 "metadata": {},
489 "output_type": "execute_result"
490 }
491 ],
492 "source": [
493 "sentences['es'][:3] "
494 ]
495 },
496 {
497 "cell_type": "markdown",
498 "metadata": {
499 "slideshow": {
500 "slide_type": "slide"
501 }
502 },
503 "source": [
504 "### Create n-grams"
505 ]
506 },
507 {
508 "cell_type": "code",
509 "execution_count": 14,
510 "metadata": {
511 "ExecuteTime": {
512 "end_time": "2018-12-07T00:07:42.030674Z",
513 "start_time": "2018-12-07T00:07:42.026289Z"
514 },
515 "slideshow": {
516 "slide_type": "fragment"
517 }
518 },
519 "outputs": [],
520 "source": [
521 "def create_ngrams(language, max_length=3):\n",
522 " \"\"\"Using gensim to create ngrams\"\"\"\n",
523 " \n",
524 " path = Path('vocab', SOURCE, language)\n",
525 " n_grams = pd.DataFrame()\n",
526 " start = time()\n",
527 " for n in range(2, max_length + 1):\n",
528 " print(n, end=' ')\n",
529 " \n",
530 " sentences = LineSentence(str(path / 'ngrams_{}.txt'.format(n-1)))\n",
531 " phrases = Phrases(sentences, threshold=100, min_count=10)\n",
532 "\n",
533 " s = pd.Series({k.decode('utf-8'): v for k,\n",
534 " v in phrases.export_phrases(sentences)}) \n",
535 " s = s.to_frame('score').reset_index().rename(\n",
536 " columns={'index': 'phrase'}).assign(length=n)\n",
537 " \n",
538 " n_grams = pd.concat([n_grams, s])\n",
539 " grams = Phraser(phrases)\n",
540 " sentences = grams[sentences]\n",
541 " \n",
542 " with open(path / 'ngrams_{}.txt'.format(n), 'w') as f:\n",
543 " for sentence in sentences:\n",
544 " f.write(' '.join(sentence) + '\\n')\n",
545 " \n",
546 " n_grams = n_grams.sort_values('score', ascending=False)\n",
547 " n_grams.phrase = n_grams.phrase.str.replace('_', ' ')\n",
548 " n_grams['ngram'] = n_grams.phrase.str.replace(' ', '_')\n",
549 " \n",
550 " with pd.HDFStore(Path(path.parent / 'vocab.h5')) as store:\n",
551 " store.put('/'.join([language, 'ngrams']), n_grams)\n",
552 " \n",
553 " print('\\n\\tDuration: ', format_time(time() - start))\n",
554 " print('\\tngrams: {:,d}\\n'.format(len(n_grams)))\n",
555 " print(n_grams.groupby('length').size())"
556 ]
557 },
558 {
559 "cell_type": "code",
560 "execution_count": 15,
561 "metadata": {
562 "ExecuteTime": {
563 "end_time": "2018-12-07T00:10:40.901962Z",
564 "start_time": "2018-12-07T00:07:45.209467Z"
565 },
566 "slideshow": {
567 "slide_type": "slide"
568 }
569 },
570 "outputs": [
571 {
572 "name": "stdout",
573 "output_type": "stream",
574 "text": [
575 "\n",
576 " en 2 3 \n",
577 "\tDuration: 00:00:36\n",
578 "\tngrams: 483\n",
579 "\n",
580 "length\n",
581 "2 433\n",
582 "3 50\n",
583 "dtype: int64\n",
584 "\n",
585 " es 2 3 \n",
586 "\tDuration: 00:00:37\n",
587 "\tngrams: 508\n",
588 "\n",
589 "length\n",
590 "2 462\n",
591 "3 46\n",
592 "dtype: int64\n"
593 ]
594 }
595 ],
596 "source": [
597 "for language in LANGUAGES:\n",
598 " print('\\n', language, end=' ')\n",
599 " create_ngrams(language)"
600 ]
601 },
602 {
603 "cell_type": "code",
604 "execution_count": null,
605 "metadata": {},
606 "outputs": [],
607 "source": []
608 }
609 ],
610 "metadata": {
611 "celltoolbar": "Slideshow",
612 "kernelspec": {
613 "display_name": "Python 3",
614 "language": "python",
615 "name": "python3"
616 },
617 "language_info": {
618 "codemirror_mode": {
619 "name": "ipython",
620 "version": 3
621 },
622 "file_extension": ".py",
623 "mimetype": "text/x-python",
624 "name": "python",
625 "nbconvert_exporter": "python",
626 "pygments_lexer": "ipython3",
627 "version": "3.6.8"
628 },
629 "toc": {
630 "base_numbering": 1,
631 "nav_menu": {},
632 "number_sections": true,
633 "sideBar": true,
634 "skip_h1_title": true,
635 "title_cell": "Table of Contents",
636 "title_sidebar": "Contents",
637 "toc_cell": false,
638 "toc_position": {
639 "height": "47px",
640 "left": "1227px",
641 "top": "40px",
642 "width": "212px"
643 },
644 "toc_section_display": true,
645 "toc_window_display": true
646 }
647 },
648 "nbformat": 4,
649 "nbformat_minor": 2
650 }