<commit_before><commit_msg>finance tools as jupyter notebook<commit_after>{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import json\n",
    "import pandas as pd\n",
    "import requests\n",
    "from bs4 import BeautifulSoup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def import_reference_file():\n",
    "    _stock_reference = pd.read_csv('C:\\\\ProgramData\\\\Anaconda3\\\\Lib\\\\site-packages\\\\toolbelt_dev\\\\_stock_reference.txt', sep = '\\t', encoding = 'latin-1')\n",
    "    _stock_reference['exchange'] = _stock_reference['Exchange:Ticker'].str.split(\":\").str[0]\n",
    "    _stock_reference['ticker'] = _stock_reference['Exchange:Ticker'].str.split(\":\").str[1]\n",
    "    _stock_reference['ticker'] = _stock_reference['ticker'].str.upper()\n",
    "    _stock_reference = _stock_reference.drop(labels=['Exchange:Ticker'], axis=1)\n",
    "    _stock_reference = _stock_reference.set_index('ticker')\n",
    "    for col in _stock_reference.columns.values:\n",
    "        _stock_reference[col] = pd.to_numeric(_stock_reference[col], errors='coerce')\n",
    "    return _stock_reference\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_valuation(ticker, minority_discount=0.2):\n",
    "    _key_metrics = {}\n",
    "    # ensure the ticker is uppercase\n",
    "    ticker = ticker.upper()\n",
    "    _key_metrics['ticker'] = ticker\n",
    "\n",
    "    # load expanded financial data from reference file\n",
    "    _stock_reference = import_reference_file().loc[ticker]\n",
    "    if _stock_reference.empty:\n",
    "        print(\"Ticker Error: Ticker not in reference file.\")\n",
    "        return None\n",
    "\n",
    "    # retrieve current price of the stock by ticker\n",
    "    current_prices = pd.DataFrame(get_current(ticker)['Time Series (1min)']).transpose().reset_index()\n",
    "    _key_metrics['current_price'] = float(\n",
    "        current_prices[current_prices['index'] == current_prices['index'].max()][\"4. close\"].iloc[0])\n",
    "\n",
    "    # ratios\n",
    "    _key_metrics['pe_ratio'] = _stock_reference['P_LTM Diluted EPS Before Extra']\n",
    "    _key_metrics['ev_ebitda'] = _stock_reference['Total Enterprise Value'] / _stock_reference['EBITDA']\n",
    "    _key_metrics['ev_bv'] = _stock_reference['Total Enterprise Value'] / (_stock_reference['Total Assets'] -\n",
    "                                                                          _stock_reference['Total Liabilities'])\n",
    "    _key_metrics['bv_share'] = (_stock_reference['Total Assets'] -\n",
    "                                _stock_reference['Total Liabilities']) / _stock_reference['Shares Outstanding']\n",
    "    _key_metrics['profit_margin'] = _stock_reference['Gross Margin'] / 100\n",
    "    _key_metrics['operating_margin'] = _stock_reference['Earnings from Cont Ops Margin'] / 100\n",
    "    _key_metrics['roa'] = _stock_reference['Return on Assets'] / 100\n",
    "    _key_metrics['roe'] = _stock_reference['Return on Equity'] / 100\n",
    "    _key_metrics['debt_equity'] = _stock_reference['Total Debt_Equity'] / 100\n",
    "\n",
    "    # graham\n",
    "    _key_metrics['graham_value'] = (_stock_reference['Diluted EPS Incl Extra Items'] *\n",
    "                                    (8.5 + (2 * (_stock_reference['LT EPS Growth Rate']))) * 4.4) / \\\n",
    "                                   (get_corporate_rates()['Yield'].iloc[0] * 100)\n",
    "    _key_metrics['graham_safety'] = 1 - (_key_metrics['current_price'] / _key_metrics['graham_value'])\n",
    "\n",
    "    # Rate lookups\n",
    "    _df_federal_rates = get_fed_rates()\n",
    "    _fed10yr = _df_federal_rates[_df_federal_rates.Date == _df_federal_rates.Date.max()]['10yr'].iloc[0]\n",
    "    _key_metrics['10yr_fed_rate'] = _fed10yr\n",
    "    _inflation = get_inflation()\n",
    "    _key_metrics['curr_inflation'] = _inflation\n",
    "\n",
    "    # Intrinsic Value\n",
    "    _key_metrics['book_value'] = (_stock_reference['Total Assets']-_stock_reference['Total Liabilities'])*1000000\n",
    "    _key_metrics['last_annual_earnings'] = _stock_reference['Diluted EPS Incl Extra Items'] * \\\n",
    "        _stock_reference['Shares Outstanding']*1000000\n",
    "\n",
    "    # 1yr growth rate\n",
    "    if not pd.isnull(_stock_reference['Est Annual EPS Growth  1 Yr']):\n",
    "        _key_metrics['1yr_growth_rate'] = _stock_reference['Est Annual EPS Growth  1 Yr']/100\n",
    "    elif not pd.isnull(_stock_reference['LT EPS Growth Rate']):\n",
    "        _key_metrics['1yr_growth_rate'] = ((_stock_reference['LT EPS Growth Rate']/100)+1)**(1/5)-1\n",
    "    elif not pd.isnull(_stock_reference['Diluted EPS before Extra 10 Yr CAGR']):\n",
    "        _key_metrics['1yr_growth_rate'] = _stock_reference['Diluted EPS before Extra 10 Yr CAGR']/100\n",
    "    else:\n",
    "        _key_metrics['1yr_growth_rate'] = 0\n",
    "    # Current Year Projected Earnings\n",
    "    if _key_metrics['last_annual_earnings'] > 0:\n",
    "        _key_metrics['cy_proj_earn'] = _key_metrics['last_annual_earnings']*(1+_key_metrics['1yr_growth_rate'])\n",
    "    else:\n",
    "        _key_metrics['cy_proj_earn'] = 0\n",
    "    _key_metrics['pv_cy_proj'] = _key_metrics['cy_proj_earn']/(1+_fed10yr)\n",
    "\n",
    "    # 2yr Growth Rate\n",
    "    if not pd.isnull(_stock_reference['Est Annual EPS Growth  2 Yr']):\n",
    "        _key_metrics['2yr_growth_rate'] = _stock_reference['Est Annual EPS Growth  2 Yr']/100\n",
    "    elif not pd.isnull(_stock_reference['LT EPS Growth Rate']):\n",
    "        _key_metrics['2yr_growth_rate'] = ((_stock_reference['LT EPS Growth Rate']/100)+1)**(1/5)-1\n",
    "    elif not pd.isnull(_stock_reference['Diluted EPS before Extra 10 Yr CAGR']):\n",
    "        _key_metrics['2yr_growth_rate'] = _stock_reference['Diluted EPS before Extra 10 Yr CAGR']/100\n",
    "    else:\n",
    "        _key_metrics['2yr_growth_rate'] = 0\n",
    "    # Next Year Projected Earnings\n",
    "    if _key_metrics['last_annual_earnings'] > 0:\n",
    "        _key_metrics['ny_proj_earn'] = _key_metrics['cy_proj_earn']*(1+_key_metrics['2yr_growth_rate'])\n",
    "    else:\n",
    "        _key_metrics['ny_proj_earn'] = 0\n",
    "    _key_metrics['pv_ny_proj'] = _key_metrics['ny_proj_earn']/((1+_fed10yr)**2)\n",
    "\n",
    "    # Long Term Growth Rate\n",
    "    if not pd.isnull(_stock_reference['LT EPS Growth Rate']):\n",
    "        _key_metrics['lt_growth_rate'] = ((_stock_reference['LT EPS Growth Rate']/100)+1)**(1/5)-1\n",
    "    elif not pd.isnull(_stock_reference['Diluted EPS before Extra 10 Yr CAGR']):\n",
    "        _key_metrics['lt_growth_rate'] = _stock_reference['Diluted EPS before Extra 10 Yr CAGR']/100\n",
    "    else:\n",
    "        _key_metrics['lt_growth_rate'] = 0\n",
    "    # Present Value of Long Term Projections\n",
    "    if _key_metrics['ny_proj_earn'] > 0:\n",
    "        _key_metrics['pv_lt_proj'] = (_key_metrics['ny_proj_earn']*(((1+_key_metrics['lt_growth_rate'])**1) / ((1+_fed10yr)**3))) +\\\n",
    "                                     (_key_metrics['ny_proj_earn']*(((1+_key_metrics['lt_growth_rate'])**2) / ((1+_fed10yr)**4))) + \\\n",
    "                                     (_key_metrics['ny_proj_earn']*(((1+_key_metrics['lt_growth_rate'])**3) / ((1+_fed10yr)**5))) + \\\n",
    "                                     (_key_metrics['ny_proj_earn']*(((1+_key_metrics['lt_growth_rate'])**4) / ((1+_fed10yr)**6))) + \\\n",
    "                                     (_key_metrics['ny_proj_earn']*(((1+_key_metrics['lt_growth_rate'])**5) / ((1+_fed10yr)**7))) + \\\n",
    "                                     (_key_metrics['ny_proj_earn']*(((1+_key_metrics['lt_growth_rate'])**6) / ((1+_fed10yr)**8))) + \\\n",
    "                                     (_key_metrics['ny_proj_earn']*(((1+_key_metrics['lt_growth_rate'])**7) / ((1+_fed10yr)**9))) + \\\n",
    "                                     (_key_metrics['ny_proj_earn']*(((1+_key_metrics['lt_growth_rate'])**8) / ((1+_fed10yr)**10)))\n",
    "    else:\n",
    "        _key_metrics['pv_lt_proj'] = 0\n",
    "    # Present value of all future earnings\n",
    "    if _key_metrics['last_annual_earnings'] > 0:\n",
    "        _key_metrics['pv_future_earnings'] = (_key_metrics['ny_proj_earn'] *\n",
    "                                              ((((1+_key_metrics['lt_growth_rate'])**8)/((1+_fed10yr)**10)) *\n",
    "                                              (((((1+_inflation)**1)/(1+_fed10yr)**1)+(((1+_inflation)**2)/(1+_fed10yr)**2) +\n",
    "                                               (((1+_inflation)**3)/((1+_fed10yr)**3))+(((1+_inflation)**4)/(1+_fed10yr)**4) +\n",
    "                                               (((1+_inflation)**5)/((1+_fed10yr)**5))+(((1+_inflation)**6)/(1+_fed10yr)**6) +\n",
    "                                               (((1+_inflation)**7)/((1+_fed10yr)**7))+(((1+_inflation)**8)/(1+_fed10yr)**8) +\n",
    "                                               (((1+_inflation)**9)/((1+_fed10yr)**9))+((1+_inflation)**10)))))\n",
    "    else:\n",
    "        _key_metrics['pv_future_earnings'] = 0\n",
    "    _key_metrics['intrinsic_value'] = _key_metrics['book_value'] + _key_metrics['pv_cy_proj'] + \\\n",
    "        _key_metrics['pv_ny_proj'] + _key_metrics['pv_lt_proj'] + \\\n",
    "        _key_metrics['pv_future_earnings']\n",
    "\n",
    "    _key_metrics['iv_per_share'] = _key_metrics['intrinsic_value'] / (_stock_reference['Shares Outstanding'] * 1000000)\n",
    "    _key_metrics['iv_safety_margin'] = 1-(_key_metrics['current_price'] / _key_metrics['iv_per_share'])\n",
    "    _key_metrics['intrinsic_fmv'] = _key_metrics['iv_per_share']*(1-minority_discount)\n",
    "    # Margin of Safety at FMV\n",
    "    if _key_metrics['intrinsic_fmv'] > 0:\n",
    "        _key_metrics['fmv_safety_margin'] = 1-(_key_metrics['current_price']/_key_metrics['intrinsic_fmv'])\n",
    "    else:\n",
    "        _key_metrics['fmv_safety_margin'] = None\n",
    "\n",
    "    return _key_metrics\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style>\n",
       "    .dataframe thead tr:only-child th {\n",
       "        text-align: right;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Issuer</th>\n",
       "      <th>Cupon</th>\n",
       "      <th>Maturity</th>\n",
       "      <th>Moody</th>\n",
       "      <th>S&amp;P</th>\n",
       "      <th>Fitch</th>\n",
       "      <th>Last</th>\n",
       "      <th>Change</th>\n",
       "      <th>Yield</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Johnson &amp; Johnson JNJ4340193</td>\n",
       "      <td>2.45%</td>\n",
       "      <td>Mar '12026</td>\n",
       "      <td>Aaa</td>\n",
       "      <td>AAA</td>\n",
       "      <td>AAA</td>\n",
       "      <td>95.418</td>\n",
       "      <td>+0.468</td>\n",
       "      <td>0.0304</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Verizon Communications Inc VZ4466757</td>\n",
       "      <td>4.13%</td>\n",
       "      <td>Mar '12027</td>\n",
       "      <td>NR</td>\n",
       "      <td>BBB+</td>\n",
       "      <td>A-</td>\n",
       "      <td>100.856</td>\n",
       "      <td>+0.27</td>\n",
       "      <td>0.0402</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Sumitomo Mitsui Finl Group Inc SMFG4381271</td>\n",
       "      <td>2.06%</td>\n",
       "      <td>Jul '12021</td>\n",
       "      <td>A1</td>\n",
       "      <td>A-</td>\n",
       "      <td>n.a.</td>\n",
       "      <td>96.905</td>\n",
       "      <td>0.105</td>\n",
       "      <td>0.0283</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Total Cap Cda Ltd TOT3954266</td>\n",
       "      <td>1.45%</td>\n",
       "      <td>Jan '12018</td>\n",
       "      <td>Aa3</td>\n",
       "      <td>A+</td>\n",
       "      <td>AA-</td>\n",
       "      <td>100.062</td>\n",
       "      <td>+0.303</td>\n",
       "      <td>0.0137</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Bnp Paribas / Bnp Paribas Us Medium Term BNPQF...</td>\n",
       "      <td>2.38%</td>\n",
       "      <td>Sep '12017</td>\n",
       "      <td>A1</td>\n",
       "      <td>A</td>\n",
       "      <td>A+</td>\n",
       "      <td>100.334</td>\n",
       "      <td>+0.051</td>\n",
       "      <td>0.0167</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>Verizon Communications Inc VZ4466641</td>\n",
       "      <td>5.50%</td>\n",
       "      <td>Mar '12047</td>\n",
       "      <td>NR</td>\n",
       "      <td>BBB+</td>\n",
       "      <td>A-</td>\n",
       "      <td>103.955</td>\n",
       "      <td>+1.03</td>\n",
       "      <td>0.0524</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>Petroleos Mexicanos PEMX4342501</td>\n",
       "      <td>4.50%</td>\n",
       "      <td>Jan '12026</td>\n",
       "      <td>Baa3</td>\n",
       "      <td>BBB+</td>\n",
       "      <td>BBB+</td>\n",
       "      <td>96.306</td>\n",
       "      <td>+2.31</td>\n",
       "      <td>0.0502</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>Abbott Labs ABT4427939</td>\n",
       "      <td>3.75%</td>\n",
       "      <td>Nov '12026</td>\n",
       "      <td>Baa3</td>\n",
       "      <td>BBB</td>\n",
       "      <td>BBB</td>\n",
       "      <td>99.12</td>\n",
       "      <td>+0.194</td>\n",
       "      <td>0.0386</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>Altria Group Inc MO.HC</td>\n",
       "      <td>9.70%</td>\n",
       "      <td>Nov '12018</td>\n",
       "      <td>A3</td>\n",
       "      <td>A-</td>\n",
       "      <td>BBB+</td>\n",
       "      <td>112.542</td>\n",
       "      <td>+0.083</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>Verizon Communications Inc VZ4466640</td>\n",
       "      <td>5.25%</td>\n",
       "      <td>Mar '12037</td>\n",
       "      <td>NR</td>\n",
       "      <td>BBB+</td>\n",
       "      <td>A-</td>\n",
       "      <td>102.51</td>\n",
       "      <td>+0.493</td>\n",
       "      <td>0.0505</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                              Issuer  Cupon    Maturity Moody  \\\n",
       "0                       Johnson & Johnson JNJ4340193  2.45%  Mar '12026   Aaa   \n",
       "1               Verizon Communications Inc VZ4466757  4.13%  Mar '12027    NR   \n",
       "2         Sumitomo Mitsui Finl Group Inc SMFG4381271  2.06%  Jul '12021    A1   \n",
       "3                       Total Cap Cda Ltd TOT3954266  1.45%  Jan '12018   Aa3   \n",
       "4  Bnp Paribas / Bnp Paribas Us Medium Term BNPQF...  2.38%  Sep '12017    A1   \n",
       "5               Verizon Communications Inc VZ4466641  5.50%  Mar '12047    NR   \n",
       "6                    Petroleos Mexicanos PEMX4342501  4.50%  Jan '12026  Baa3   \n",
       "7                             Abbott Labs ABT4427939  3.75%  Nov '12026  Baa3   \n",
       "8                             Altria Group Inc MO.HC  9.70%  Nov '12018    A3   \n",
       "9               Verizon Communications Inc VZ4466640  5.25%  Mar '12037    NR   \n",
       "\n",
       "    S&P Fitch     Last  Change   Yield  \n",
       "0   AAA   AAA   95.418  +0.468  0.0304  \n",
       "1  BBB+    A-  100.856   +0.27  0.0402  \n",
       "2    A-  n.a.   96.905  0.105  0.0283  \n",
       "3    A+   AA-  100.062  +0.303  0.0137  \n",
       "4     A    A+  100.334  +0.051  0.0167  \n",
       "5  BBB+    A-  103.955   +1.03  0.0524  \n",
       "6  BBB+  BBB+   96.306   +2.31  0.0502  \n",
       "7   BBB   BBB    99.12  +0.194  0.0386  \n",
       "8    A-  BBB+  112.542  +0.083     NaN  \n",
       "9  BBB+    A-   102.51  +0.493  0.0505  "
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def get_corporate_rates():\n",
    "    _url = \"http://markets.on.nytimes.com/research/markets/bonds/bonds.asp\"\n",
    "    _r = requests.get(_url)\n",
    "    _soup = BeautifulSoup(_r.text, 'lxml')\n",
    "    _table = _soup.find(class_=\"finra\")\n",
    "    _subtable = _table.find_all('tbody')[0]\n",
    "    df_columns = ['Issuer', 'Cupon', 'Maturity', 'Moody', 'S&P', 'Fitch', 'Last', 'Change', 'Yield']\n",
    "    df_lists = []\n",
    "    for row in _subtable.find_all('tr'):\n",
    "        row_list = []\n",
    "        for col in row.find_all('td'):\n",
    "            row_list.append(col.text)\n",
    "        df_lists.append(row_list)\n",
    "    df = pd.DataFrame(df_lists, columns=df_columns)\n",
    "    df['Yield'] = pd.to_numeric(df['Yield'].map(lambda x: x.rstrip('%')), errors='coerce') / 100\n",
    "    return df\n",
    "\n",
    "# Get entire table of corporate rates\n",
    "get_corporate_rates()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.028300000000000002"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def get_fed_rates():\n",
    "    _url = \"https://www.treasury.gov/resource-center/data-chart-center/interest-rates/Pages/TextView.aspx?data=yield\"\n",
    "    _r = requests.get(_url)\n",
    "    _soup = BeautifulSoup(_r.text, 'lxml')\n",
    "    _table = _soup.find(class_='t-chart')\n",
    "    df_columns = ['Date', '1mo', '3mo', '6mo', '1yr', '2yr', '3yr', '5yr', '7yr', '10yr', '20yr', '30yr']\n",
    "    df_lists = []\n",
    "    # Find all the <tr> tag pairs, skip the first one, then for each.\n",
    "    for row in _table.find_all('tr')[1:]:\n",
    "        row_list = []\n",
    "        for col in row.find_all('td'):\n",
    "            row_list.append(col.string.strip())\n",
    "        df_lists.append(row_list)\n",
    "    df = pd.DataFrame(df_lists, columns=df_columns)\n",
    "    df.Date = pd.to_datetime(df.Date)\n",
    "    for col in df_columns[1:]:\n",
    "        df[col] = pd.to_numeric(df[col], errors='coerce')/100\n",
    "    return df\n",
    "\n",
    "# Get current fed 30yr rate\n",
    "df = get_fed_rates()\n",
    "df[df.Date == df.Date.max()]['30yr'].iloc[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0008"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def get_inflation():\n",
    "    _url = \"https://www.statbureau.org/en/united-states/inflation\"\n",
    "    _r = requests.get(_url)\n",
    "    _soup = BeautifulSoup(_r.text, 'lxml')\n",
    "    _table = _soup.find(class_=\"currnet-inflation-table\")\n",
    "    _rate_str = _table.find_all('tr')[0].find_all('td')[1].string.strip()\n",
    "    return float(_rate_str.split('%')[0]) / 100\n",
    "\n",
    "# Get current inflation rates\n",
    "get_inflation()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "74.155"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def get_current(ticker):\n",
    "    ticker = ticker.upper()\n",
    "    with open('C:\\\\Users\\\\ajwilson\\\\Documents\\\\GitHub\\\\toolbelt_dev\\\\toolbelt\\\\alphavantage_api.json', 'r') as j:\n",
    "        credentials = json.load(j)\n",
    "    _url = \"https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=\" + ticker + \\\n",
    "           \"&interval=1min&apikey=\" + credentials['api_key']\n",
    "    _r = requests.get(url=_url)\n",
    "    return _r.json()\n",
    "\n",
    "# Pull current MSFT Price\n",
    "current_prices = pd.DataFrame(get_current(\"MSFT\")['Time Series (1min)']).transpose().reset_index()\n",
    "float(current_prices[current_prices['index'] == current_prices['index'].max()][\"4. close\"].iloc[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def export_valuation(ticker, location=os.getcwd(), minority_discount=0.2):\n",
    "    _values = get_valuation(ticker, minority_discount)\n",
    "    _column_keys = ['ticker','current_price', 'pe_ratio', 'ev_ebitda', 'ev_bv', 'bv_share', 'profit_margin',\n",
    "                    'operating_margin', 'roa', 'roe', 'debt_equity', 'graham_value', 'graham_safety', 'intrinsic_fmv',\n",
    "                    'fmv_safety_margin', 'book_value', 'last_annual_earnings', '1yr_growth_rate', 'cy_proj_earn',\n",
    "                    'pv_cy_proj', '2yr_growth_rate', 'ny_proj_earn', 'pv_ny_proj', 'lt_growth_rate', 'pv_lt_proj',\n",
    "                    'pv_future_earnings', 'intrinsic_value', 'iv_per_share', 'iv_safety_margin']\n",
    "    _column_titles = ['Ticker', 'Current Price', 'P/E Ratio', 'EV/EBITDA', 'EV/BV', 'BV/Share', 'Profit Margin',\n",
    "                      'Operation Margin', 'Return on Assets', 'Return on Equity', 'Debt/Equity Ratio', 'Graham Value',\n",
    "                      'Graham Margin of Safety', 'Intrinsic FMV w/ Minority Discount', 'Intrinsic FMV Margin of Safety',\n",
    "                      'Book Value of Equity', 'Last Annual Earnings', 'Annual Growth Rate for Current Year Projections',\n",
    "                      'Current Year Projected Earnings', 'Present Value of CY Projection',\n",
    "                      'Annual Growth Rate for Next Year Projections', 'Next Year Projected Earnings',\n",
    "                      'Present Value of NY Projection', 'Annual Grow Rate for 3-10 Year Projections',\n",
    "                      'Present Value of 3-10 Year Projections', 'Present Value of all Future Earnings',\n",
    "                      'Intrinsic Value', 'Intrinsic Value per Share', 'Margin of Safety for Intrinsic Value']\n",
    "    _column_data = []\n",
    "    for col in _column_keys:\n",
    "        _column_data.append(_values[col])\n",
    "    _df = pd.DataFrame(data=[_column_data], columns=_column_titles)\n",
    "    _df.to_csv(os.path.join(location, (_values[\"ticker\"]+\".csv\")), index=False)\n",
    "\n",
    "# Export full MSFT valuation to the given directory location    \n",
    "export_valuation(\"MSFT\",\"C:\\\\Users\\\\ajwilson\\\\Desktop\\\\\")"
   ]
  }
 ],
 "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.6.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
{'fraction_non_alphanumeric': 0.20829565074405984, 'fraction_numerical': 0.03917619008468305, 'mean_word_length': 1.9696044921875, 'pattern_counts': {'":': 84, '<': 256, '<?xml version=': 0, '>': 261, 'https://': 3, 'lorem ipsum': 0, 'www.': 3, 'xml': 3}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 37, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6164284', 'n_tokens_mistral': 9894, 'n_tokens_neox': 9162, 'n_words': 1350}