{ "cells": [ { "cell_type": "markdown", "metadata": { "heading_collapsed": true }, "source": [ "### Библиотеки / данные" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "импортируем библиотеки numpy и pandas" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "импортируем библиотеку matplotlib для построения графиков" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "задаем некоторые настройки pandas, регулирующие формат вывода" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "pd.options.display.max_rows = 10" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "- считываем данные \n", "- используем столбец Symbol в качестве индекса \n", "- считываем только те столбцы ['Symbol', 'Sector', 'Price', 'Book Value', 'Market Cap', 'Dividend Yield']" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "| Column Name | Description\n", "| ------------- |:-------------:|\n", "|Symbol|Сокращенное название организации|\n", "|Name|Полное название организации|\n", "|Sector|Сектор экономики|\n", "|Price|Стоимость акции|\n", "|Dividend Yield|Дивидендная доходность|\n", "|Price/Earnings|Цена / прибыль|\n", "|Earnings/Share|Прибыль на акцию|\n", "|Book Value|Балансовая стоимость компании|\n", "|52 week low|52-недельный минимум|\n", "|52 week high|52-недельный максимум|\n", "|Market Cap|Рыночная капитализация|\n", "|EBITDA|**E**arnings **b**efore **i**nterest, **t**axes, **d**epreciation and **a**mortization|\n", "|Price/Sales|Цена / объём продаж|\n", "|Price/Book|Цена / балансовая стоимость|\n", "|SEC Filings|Ссылка *sec.gov*|" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "sp500 = pd.read_csv(\"../data/sp500.csv\",\n", " index_col='Symbol',\n", " usecols=['Symbol', 'Sector', 'Price',\n", " 'Book Value', 'Market Cap',\n", " 'Dividend Yield'])\n", "sp500" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "считываем исторические данные о котировках акций" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh = pd.read_csv('../data/omh.csv', \n", " parse_dates=['Date'])\n", "\n", "omh.set_index('Date', \n", " inplace=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh.head()" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true }, "source": [ "### Настройка " ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true, "hidden": true }, "source": [ "#### пример " ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "график цены акции Microsoft" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh.MSFT.plot()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "цена акций microsoft и apple на одном графике" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh.plot()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "нормализация:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh_copy = (omh - omh.mean())/omh.std()\n", "omh_copy.plot()" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true, "hidden": true }, "source": [ "#### размер " ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "увеличиваем размер графика" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh_copy.plot(figsize=(10, 5))" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true, "hidden": true }, "source": [ "#### заголовок / подписи" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "- заголовок задаем с помощью параметра title метода .plot()\n", "- после вызова метода .plot() явно задаем подписи осей x и y" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh_copy.plot(title='Цены акций после нормировки')\n", "plt.xlabel('Дата')\n", "plt.ylabel('Цена')" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true, "hidden": true }, "source": [ "#### легенда" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "изменяем элементы легенды, соответствующие именам столбцов датафрейма" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "ax = omh_copy.plot()\n", "ax.legend(['Microsoft', 'Apple'])" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "изменяем расположение легенды" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "ax = omh_copy.plot()\n", "ax.legend(loc='upper center')" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "отключаем легенду с помощью legend=False" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh_copy.plot(legend=False)" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true, "hidden": true }, "source": [ "#### цвет / стиль / толщина / маркер" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "меняем цвета линий графика \n", "[односимвольные коды](https://matplotlib.org/2.0.2/api/colors_api.html) \n", "[шестнадцатеричный RGB-код](https://www.rapidtables.com/web/color/RGB_Color.html)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh_copy.plot(style={'MSFT': '#0000FF', 'AAPL': 'g'}) " ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "- [различные стили линий](https://matplotlib.org/1.5.3/api/pyplot_api.html#matplotlib.pyplot.plot) \n", "- увеличиваем толщину линий" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh_copy.plot(style={'MSFT': 'b--', 'AAPL': 'g:'}, lw=3)" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "рисуем заново, добавив [маркеры](https://matplotlib.org/api/markers_api.html) линий" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh_copy.plot(style={'MSFT': 'b--^', 'AAPL': 'g:o'})" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true }, "source": [ "### Графики" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true, "hidden": true }, "source": [ "#### bar" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "строим столбчатую диаграмму" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "s = sp500.Sector.value_counts()\n", "s.plot(kind='bar')" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "малочисленные сектора:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "small_sectors = s[-4:].index.values\n", "small_sectors" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "95% квантиль" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "sp500.quantile(0.95)" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "создаем копию данных sp500 " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "ind = (~sp500.Sector.isin(small_sectors)) \\\n", " & (sp500.Price < 184) \\\n", " & (sp500['Book Value'] < 66) \\\n", " & (sp500['Market Cap'] < 134) \\\n", " & (sp500['Dividend Yield'] < 4.5)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "sp500_cut = sp500.loc[ind].copy()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "sp500_cut.shape" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "строим столбчатую диаграмму на основе нескольких серий" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df = sp500_cut.groupby('Sector').Price.agg(['mean', 'median'])\n", "df.plot(kind='bar', figsize=(10, 5))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "вертикальная состыкованная столбчатая диаграмма" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df.plot(kind='bar', stacked=True, figsize=(10, 5));" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "горизонтальная состыкованная столбиковая диаграмма" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df.plot(kind='barh', stacked=True, figsize=(10, 5));" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true, "hidden": true }, "source": [ "#### hist" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "строим гистограмму" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "sp500_cut.Price.hist()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "снова строим гистограмму, но теперь с большим количеством интервалов (бинов)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "sp500_cut.Price.hist(bins = 50);" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "поскольку у нас 4 столбца, pandas строит четыре гистограммы" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "sp500_cut.hist(figsize=(12,8))" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "напрямую воспользуемся модулем pyplot для наложения нескольких гистограмм" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "plt.figure(figsize=(12, 6))\n", "plt.hist(sp500_cut.Price, alpha=0.5, label='Price')\n", "plt.hist(sp500_cut['Book Value'], alpha=0.5, label='Book Value')\n", "plt.legend(loc='upper right');" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "s = sp500_cut.Price\n", "s.hist(density=True)\n", "s.plot(kind='kde', figsize=(10,6))" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true, "hidden": true }, "source": [ "#### box" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "sp500_cut[['Price','Book Value']].boxplot(figsize = (14, 7))" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true, "hidden": true }, "source": [ "#### scatter" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "sp500_cut.plot(kind='scatter', x='Price', y='Book Value', figsize=(10, 6));" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "from pandas.plotting import scatter_matrix\n", "scatter_matrix(sp500_cut, alpha=0.4, figsize=(9, 9), diagonal='kde');" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true, "hidden": true }, "source": [ "#### heat map" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "corr_matrix = sp500_cut.corr()\n", "corr_matrix" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "plt.figure(figsize=(7, 7))\n", "plt.imshow(corr_matrix, cmap='Greens')\n", "plt.colorbar() # добавим шкалу интенсивности цвета\n", "\n", "plt.xticks(range(len(corr_matrix.columns)), corr_matrix.columns)\n", "plt.yticks(range(len(corr_matrix)), corr_matrix.index);" ] } ], "metadata": { "hide_input": false, "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.7.0" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": true } }, "nbformat": 4, "nbformat_minor": 2 }