{ "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": [ "задаем некоторые настройки 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']" ] }, { "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', 'Book Value'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "sp500.head()" ] }, { "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": {}, "source": [ "### Сводка статистик" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "получаем сводку статистик для датафрейма, с которой работаем как с обычным датафреймом" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sp500.describe()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "вычисляем сводку статистик для отдельного столбца Price" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sp500.Price.describe()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "получаем сводку статистик для нечисловых данных" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sp500.Sector.describe()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "метод info:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sp500.info()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "получаем сводную статистику для нечисловых данных" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sp500.Sector.value_counts(normalize=True)" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true }, "source": [ "### Арифметические операции" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "- задаем стартовое значение генератора случайных чисел для получения воспроизводимых результатов\n", "- создаем объект DataFrame" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "np.random.seed(123)\n", "df = pd.DataFrame(np.random.randn(5, 4), \n", " columns=['A', 'B', 'C', 'D'])\n", "df" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "умножаем все на 2, берём только абсолютные значения" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "abs(df * 2)" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "вычитаем первую строку из каждой строки объекта DataFrame" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df.iloc[0]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df - df.iloc[0]" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "вычитаем объект DataFrame из объекта Series" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df.iloc[0] - df" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "- возьмём второе и третье поле 1-ой строки:\n", "- добавляем столбец E\n", "- смотрим, как применяется выравнивание в этой математической операции" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "s = df.iloc[0][1:3]\n", "s['E'] = 0\n", "s" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df + s" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "извлекаем строки в позициях с 1-й по 3-ю и только столбцы B и C
\n", "по сути - извлекаем небольшой квадрат из середины df" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "subframe = df[1:4][['B', 'C']].copy()\n", "subframe" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "демонстрируем, как происходит выравнивание при выполнении операции вычитания" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df - subframe" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "извлекаем столбец A и вычитаем его из нашего датафрейма" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "df.sub(df['A'], axis=0)" ] }, { "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": [ "определяем максимальную цену для обеих акций" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh[['MSFT', 'AAPL']].min()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "определяем индекс, которому соответствует максимальная цена для обеих акций" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh[['MSFT', 'AAPL']].idxmin()" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true, "hidden": true }, "source": [ "#### cреднее значение / медиана / мода" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "вычисляем среднее значение для всех столбцов в датафрейме omh" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh.mean()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "вычисляем значение, усредненное по всем столбцам, для каждой строки (выведем первые 5)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh.mean(axis=1).head() " ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "вычисляем медиану значений для каждого столбца" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh.median()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "вычисляем моду для столбца Sector" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "sp500.Sector.mode()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "мод может быть несколько, поэтому результат операции - Series " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "s = pd.Series([1, 2, 3, 3, 5, 1])\n", "s.mode()" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true, "hidden": true }, "source": [ "#### [дисперсия](https://ru.wikipedia.org/wiki/Дисперсия_случайной_величины) / среднеквадратичное отклонение" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "вычисляем дисперсию значений в каждом столбце" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh.var()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "(omh.MSFT**2 - omh.MSFT.mean()**2).sum() / (omh.shape[0]-1)" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "вычисляем среднеквадратичное отклонение" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh.std()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh.MSFT.var()**0.5" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true, "hidden": true }, "source": [ "#### [ковариация](https://ru.wikipedia.org/wiki/Ковариация) / [корреляция](https://ru.wikipedia.org/wiki/Корреляция)" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "вычисляем ковариацию между MSFT и AAPL" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh.MSFT.cov(omh.AAPL)" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "вычисляем корреляцию между MSFT и AAPL" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh.MSFT.corr(omh.AAPL)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh.MSFT.cov(omh.AAPL) / (omh.MSFT.std() * omh.AAPL.std())" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "либо можем получать матрицу ковариаций" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh.corr()" ] }, { "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": [ "генерируем 10000 случайных чисел из стандартного нормального распределения" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "np.random.seed(123456)\n", "dist = np.random.normal(size = 10000)\n", "dist" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "выводим среднее и стандартное отклонение" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "(dist.mean(), dist.std())" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "разбиваем на пять одинаковых по размеру групп (по размеру интервалов - не количеству наблюдений в группе!)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "bins = pd.cut(dist, 5)\n", "bins" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "найдём длины соответствующих интервалов" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "bins.categories" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true, "scrolled": true }, "outputs": [], "source": [ "[q.right - q.left for q in bins.categories]" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "генерируем 50 значений возраста в диапазоне от 6 до 70" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "np.random.seed(242)\n", "ages = np.random.randint(6, 70, 50)\n", "ages" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "добавляем имена для групп" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "ranges = [6, 12, 18, 35, 50, 70]\n", "labels = ['Youth', 'Young Adult', 'Adult', 'Middle Aged', 'Retired persons']\n", "agebins = pd.cut(ages, ranges, labels=labels)\n", "agebins.describe()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "разбиваем (используя квантили) на 5 групп с одинаковым количеством элементов" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "qbin = pd.qcut(dist, 5)" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "найдём статистику по полученным группам" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "qbin.describe()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "пример использования qcut:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "sp500_copy = sp500.copy()\n", "sp500_copy['Price_Group'], bins = pd.qcut(sp500_copy.Price, \n", " 5,\n", " labels=['group_'+str(i) for i in range(1, 6)],\n", " retbins=True)\n", "sp500_copy.Price_Group" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "bins" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "sp500_copy.Price_Group.value_counts()" ] }, { "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": [ "pd.Series([1, 2, 3, 4]).cumsum()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "вычисляем кумулятивное произведение" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "pd.Series([1, 2, 3, 4]).cumprod()" ] }, { "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": [ "s = pd.Series([160, 165, 165, 170, 175], index=list('abcde'))\n", "s" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "ранжируем значения" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "s.rank()" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true, "hidden": true }, "source": [ "#### относительное изменение" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh[['MSFT']].head()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "вычисляем относительнон изменение для MSFT (текущее значение с предыдущим)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh[['MSFT']].pct_change().head()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "(48.46 - 48.62)/48.62" ] }, { "cell_type": "markdown", "metadata": { "heading_collapsed": true }, "source": [ "### Оконные функции" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "Объект Rolling:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "r = omh.MSFT.rolling(3)" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "возможные операции:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "r." ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "скользящее среднее:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "r.mean()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "первое значение:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh.MSFT.loc['2014-12-01':'2014-12-03'].mean()" ] }, { "cell_type": "markdown", "metadata": { "hidden": true }, "source": [ "второе:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hidden": true }, "outputs": [], "source": [ "omh.MSFT.loc['2014-12-02':'2014-12-04'].mean()" ] } ], "metadata": { "anaconda-cloud": {}, "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": { "height": "calc(100% - 180px)", "left": "10px", "top": "150px", "width": "301.788px" }, "toc_section_display": true, "toc_window_display": true } }, "nbformat": 4, "nbformat_minor": 1 }