Ejemplo n.º 1
0
def get_lab_exercise() -> LabExercise:
    pd_mono = pl.Monospace('pandas')
    to_excel_mono = pl.Monospace('to_excel')
    bullet_contents = [
        [
            'Download "MSFT Financials.xls" from Canvas in Lab Exercises -> Read Write Excel Pandas',
            'Read the sheet "Income Statement" into a DataFrame',
            'Write the DataFrame to a new workbook, "My Data.xlsx", with the sheet '
            'name "Income Statement"'
        ],
        [[
            'Use the same "MSFT Financials.xls" from the first exercise on Slide',
            pl.Ref('lab:read-write-excel-pandas-1')
        ],
         'Output to five separate workbooks, named "My Data1.xlsx", "My Data2.xlsx", and so on.',
         [
             'Do this',
             pl.Underline('without'), 'writing the', to_excel_mono,
             'command multiple times'
         ]],
        [
            'Note: this exercise uses the Advanced material covered in Examples -> Read Write Excel Pandas',
            [
                'Use the same "MSFT Financials.xls" from the first exercise on Slide',
                pl.Ref('lab:read-write-excel-pandas-1')
            ],
            'Output to five separate sheets in the same workbook "My Data.xlsx". The sheets should '
            'be named "Income Statement 1", "Income Statement 2", and so on.',
            [
                'Do this',
                pl.Underline('without'), 'writing the', to_excel_mono,
                'command multiple times'
            ]
        ]
    ]
    return LabExercise(bullet_contents,
                       'Reading and Writing to Excel',
                       f"Reading and Writing to Excel with {pd_mono}",
                       label='lab:read-write-excel-pandas')
Ejemplo n.º 2
0
 def _title_obj(self) -> Union[Bold, Hyperlink]:
     if self.href is None:
         title = Bold(self.title)
     else:
         # Handle hyperlink
         styled_title = pl.TextColor(self.title,
                                     color=pl.RGB(50,
                                                  82,
                                                  209,
                                                  color_name='darkblue'))
         styled_title = pl.Underline(styled_title)
         title = Hyperlink(self.href, styled_title)
         self.add_data_from_content(title)
     return title
Ejemplo n.º 3
0
def get_content():
    non_cash_items = [
        'depreciation',
        'amortization',
        'stock-based compensation',
        'impairment charges',
        'gains/losses on investments'
    ]
    non_cash_str = ', '.join(non_cash_items[:-1]) + ', and ' + non_cash_items[-1]
    non_cash_eq = pl.Equation(
        str_eq=f'{pl.Text("Adjustments")} = {" + ".join([str(pl.Text(item)) for item in non_cash_items])}',
    )

    lecture = get_dcf_fcf_lecture()
    fcf_exercise = get_fcf_calculation_lab_lecture().to_pyexlatex()
    simple_ts_exercise = get_simple_forecast_lab_lecture().to_pyexlatex()
    complex_ts_exercise = get_complex_forecast_lab_lecture().to_pyexlatex()
    tv_exercise = get_dcf_tv_lab_lecture().to_pyexlatex()

    return [
        pl.Section(
            [
                lp.DimRevealListFrame(
                    [
                        'There are two main parts to the FCF part of the DCF model',
                        'First is to find all the historical FCFs. This is the straightforward part of '
                        'plugging values into set calculations.',
                        'The more difficult and important part is projecting future cash flows',
                        'We will discuss a variety of approaches for this'
                    ],
                    title='FCF Overview'
                ),
                lp.DimRevealListFrame(
                    [
                        'Free cash flow (FCF) represents cash a company earns after paying for its operations.',
                        'It is not to be confused with net income, which amortizes costs across years and '
                        'includes non-cash expenses',
                        'FCF represents only the cash flows from that year, and so can be a lot more variable than '
                        'net income',
                        'FCF is the actual cash earned, and so it is what we should use for valuation'
                    ],
                    title='What is FCF?'
                ),
                lp.TwoColumnGraphicDimRevealFrame(
                    [
                        'We can follow a simple formula to get FCFs from historical financials',
                        'All we have to do is calculate the formula for each year of historical data',
                        'Each of the components to this calculation besides net income themselves require '
                        'a calculation. In the Historical FCF section we will cover each component.',
                        'The formula is all about reversing the non-cash adjustments to net income'
                    ],
                    graphics=[
                        images_path('fcf-formula.png')
                    ],
                    title='Historical FCFs'
                ),
                lp.DimRevealListFrame(
                    [
                        'The challenge in the FCF model is to project the cash flows',
                        ['There are two main approaches to getting future FCFs:', pl.Underline('forecast the FCFs'),
                         'and', pl.Underline('forecast the financial statements.')],
                        'Forecasting FCFs is much easier but is not as accurate, both due to lack of granularity and '
                        'due to typically uneven FCFs',
                        ['We will use', pl.Underline('time-series methods'), 'to forecast the financial statements, '
                         'either in the', pl.Underline('levels'), 'of the item, the', pl.Underline('growth'),
                         'of the item, or as a', pl.Underline('percentage of another item')]
                    ],
                    title='Forecasting FCFs'
                )
            ],
            title='Overview'
        ),
        pl.Section(
            [
                SingleBlockDimRevealListFrame(
                    [
                        'Non-cash expenses is just the sum of all items on the income statement that do not '
                        'affect cash.',
                        f'This includes {non_cash_str}'
                    ],
                    block_contents=[non_cash_eq],
                    block_title='Calculate Non-Cash Expenses',
                    title='Non-Cash Expenses'
                ),
                SingleBlockDimRevealListFrame(
                    [
                        'Net Working Capital (NWC) represents cash actively tied up in daily transactions',
                        'Cacluating the change in NWC requires information from this period '
                        'as well as last period.',
                        'First, calculate the NWC in each period using accounts receivable, '
                        'inventory, and accounts payable.',
                        "Then, take the difference between this period's NWC and last to get the change"
                    ],
                    block_contents=[
                        pl.Equation(
                            str_eq=rf'\Delta{pl.Text("NWC")} = {pl.Text("NWC")}_t - {pl.Text("NWC")}_{{t-1}}',
                            inline=False
                        ),
                        pl.Equation(
                            str_eq=rf'{pl.Text("NWC")} = {pl.Text("Accounts Receivable")} + {pl.Text("Inventory")} '
                                   rf'- {pl.Text("Accounts Payable")}',
                            inline=False
                        )
                    ],
                    block_title='Calculate Change in NWC',
                    title='Change in Net Working Capital'
                ),
                SingleBlockDimRevealListFrame(
                    [
                        'Capital Expenditures (CapEx) are outlays for fixed assets which get used over time, such '
                        'as buildings or machinery.',
                        'The change in Property, Plant and Equipment from the balance sheet can be used to estimate '
                        'CapEx.',
                        'Then you just need to add back the current depreciation & amortization, as they decreased '
                        'PPE even though no cash exchanged hands'
                    ],
                    block_contents=[
                        pl.Equation(
                            str_eq=fr'{pl.Text("CapEx")} = \Delta{pl.Text("PPE")} + '
                                   fr'{pl.Text("Depreciation & Amortization")}',
                            inline=False
                        )
                    ],
                    block_title='Calculate CapEx',
                    title='Capital Expenditures'
                ),
                SingleBlockDimRevealListFrame(
                    [
                        'Again, the FCF formula takes net income and reverses the non-cash adjustments',
                        'Add back the non-cash expenses because no actual cash was spent',
                        'Decrease by the change in NWC as an increase means additional cash was used for operations',
                        'Decrease by CapEx because this cash was spent for a new building, machinery, etc.'
                    ],
                    block_contents=[
                        pl.Equation(
                            str_eq=fr'{pl.Text("FCF")} = {pl.Text("Net Income")} + {pl.Text("Non-Cash Expenses")} - '
                                   fr'\Delta{pl.Text("NWC")} - {pl.Text("CapEx")}',
                            inline=False
                        )
                    ],
                    block_title='Calculating FCF',
                    title='Put it All Together'
                ),
                InClassExampleFrame(
                    [
                        'Go to the course site and download the files in Historical FCF',
                        'There should be a Jupyter notebook as well as a data file',
                        'We will go through a couple approaches to calculating FCFs in Python.'
                    ],
                    title='Example for Calculating FCFs',
                    block_title='Two Ways to Calculate FCFs in Python'
                ),
                fcf_exercise.presentation_frames(),
            ],
            title='Calculating Historical Free Cash Flows',
            short_title='Historical FCF',
        ),
        pl.Section(
            [
                lp.DimRevealListFrame(
                    [
                        pl.TextSize(-1),
                        'As mentioned in the intro, we will use time-series methods on the levels of the item, '
                        'the growth of the item, or as a percentage of another item',
                        'Time-series methods are about numerically estimating future values based on past values',
                        'Levels mean we forecast the numbers of the item itself, e.g. sales was 1M two years ago and '
                        '1.5M last year so we feed those numbers into our time-series model and predict 2M for the '
                        'next year',
                        'Growth means to first calculate the historical growth rate of the item, then forecast that. '
                        'E.g. sales grew 10% two years ago and 8% last year so we expect it to grow 6% this year',
                        'Percentage of item methods link an item to another item. E.g. setting cost of goods sold to '
                        '60% of sales. That percentage still needs to be forecasted',
                        "Any forecast can be adjusted by the analyst's qualitative projections of the future. The "
                        "forecast method may also have to be chosen with the qualitative analysis in mind"
                    ],
                    title='Overview of the Methods'
                ),
                lp.TwoColumnGraphicDimRevealFrame(
                    [
                        'Time-series methods seek to predict the future using the past',
                        'There is a large variety of possible time-series models to use for forecasting',
                        'They each use different characteristics of the past to assist in predicting the future'
                    ],
                    graphics=[
                        images_path('time-series-linear-plot.png')
                    ],
                    title='What Are Time-Series Methods?'
                ),
                lp.DimRevealListFrame(
                    [
                        ['The simplest models are to use the', pl.Underline('average of historical values'), 'or the',
                         pl.Underline('most recent value'), 'as the prediction for all future values'],
                        ['A more realistic model will also include estimating the', pl.Underline('trend'),
                         f'or {pl.Underline("growth")} of the historical values and applying that to the future'],
                        'More advanced models use autoregressive terms (recent values predict future values), moving '
                        'average terms (recent errors predict future values), or conditional heteroskedasticity terms '
                        '(changing variance over time)',
                        'Examples of these advanced models include AR, MA, ARMA, ARCH, GAM, and many more'
                    ],
                    title='What are the Time-Series Models?'
                ),
                lp.DimRevealListFrame(
                    [
                        'The choice of a time-series model will depend on the amount of data, the frequency of the '
                        'data, and the historical patterns in the data',
                        'If the data is historically constant or expected to be constant in the future, using the '
                        'average or most recent value should be enough',
                        "If the data follows a defined trend or growth and doesn't have historical patterns, "
                        "then using the "
                        "trend or growth models should be enough",
                        'If there are historical patterns in the data, such as seasonality, then more advanced '
                        'models are required.'
                    ],
                    title='Which Time-Series Model to Use?'
                ),
                lp.DimRevealListFrame(
                    [
                        ['The best place to start is to', pl.Underline('examine the history'), 'either by a plot',
                         'or just by looking at the numbers if you only have a few'],
                        ['Based on the amount of historical data, any perceived patterns in the historical data, '
                         'and any qualitative knowledge of the data,', pl.Underline('choose a time-series model.')],
                        [pl.Underline('Fit'), 'the time-series model on historical data, then', pl.Underline('predict'),
                         'the future values using the fitted model'],
                        ['Finish by', pl.Underline('examining the forecast'), 'to ensure it worked as intended, ',
                         'typically via a plot.']
                    ],
                    title='Steps to Forecasting'
                ),
                lp.DimRevealListFrame(
                    [
                        'When we forecast levels, just use the forecasted values and you are done',
                        'When we forecast growth, calculate the historical growth, run the forecast on that, then '
                        'apply the predicted future growth from the final historical period to generate '
                        'the forecasted levels',
                        'For percentage of item methods, calculate the historical percentage of the item, '
                        'forecast future item percentages, then use these in combination with '
                        'the forecast of the referenced item to generate the prediction',
                        'E.g. use the average approach to say historically COGS was 40% of sales, and so estimate '
                        'COGS as 40% of sales going forward. Multiply the forecasted sales by 40% to get the COGS',
                    ],
                    title='What to Forecast?'
                )
            ],
            title='Approaches to Forecasting',
            short_title='Forecasting Overview'
        ),
        pl.Section(
            [
                SingleBlockDimRevealListFrame(
                    [
                        [
                            pl.Bold('Fit:'),
                            'To fit the historical average model, take an average of the historical values'
                        ],
                        [
                            pl.Bold('Predict:'),
                            'To predict, use that average value for all future values'
                        ]
                    ],
                    [
                        EquationWithVariableDefinitions(
                            r'y_{T + n} = \frac{1}{T} \sum_{t=0}^T y_t + \epsilon_t',
                            [
                                '$t$: Current time period',
                                '$T$: Last time period of historical data',
                                '$y_t$: The current value of the data',
                                '$y_T$: The last historical value of the data',
                                '$n$: Number of periods forecasted'
                            ]
                        )
                    ],
                    title='Using the Historical Average Model',
                    block_title='Historical Average Model'
                ),
                SingleBlockDimRevealListFrame(
                    [
                        [
                            pl.Bold('Fit:'),
                            'To fit the most recent value model, take the latest value.'
                        ],
                        [
                            pl.Bold('Predict:'),
                            'To predict, use that latest value for all future values'
                        ]
                    ],
                    [
                        pl.Equation(str_eq=r'y_t = y_{t-1} + \epsilon_t', inline=False)
                    ],
                    title='Using the Recent Value Model',
                    block_title='Recent Value Model'
                ),
                SingleBlockDimRevealListFrame(
                    [
                        [
                            pl.Bold('Fit:'),
                                [
                                    'Run an OLS regression with a constant and time as the independent variable, '
                                    'where time is measured in number of periods since the beginning',
                                ],
                        ],
                        [
                            pl.Bold('Predict:'),
                                [
                                    r'For each $t$ you want to predict, calculate $a + \beta t$',
                                ],
                        ]
                    ],
                    [
                        pl.Equation(str_eq=r'y_t = a + \beta t + \epsilon_t', inline=False)
                    ],
                    title='Using the Trend Model',
                    block_title='Trend Model'
                ),
                SingleBlockDimRevealListFrame(
                    [
                        [
                            pl.Bold('Fit:'),
                            [
                                'Calculate the compounded annual growth rate (CAGR) as',
                                pl.Equation(str_eq=r'\frac{y_T}{y_0}^{\frac{1}{n}} - 1')
                            ]
                        ],
                        [
                            pl.Bold('Predict:'),
                            ['Calculate future periods by compounding CAGR on the latest historical period',
                            pl.Equation(str_eq=rf'y_{{T + f}} = y_T * (1 + {pl.Text("CAGR")})^f')]
                        ]
                    ],
                    [
                        pl.Equation(str_eq=r'y_{{T + f}} = y_T * (\frac{y_T}{y_0}^{\frac{1}{n}})^f', inline=False)
                    ],
                    title='Using the CAGR Model',
                    block_title='CAGR'
                ),
                InClassExampleFrame(
                    [
                        'Go to the course site and download the files in Examples > DCF > Forecasting > Simple',
                        'There should be a Jupyter notebook as well as two Excel files. Place these all in the '
                        'same folder',
                        'We will walk through "Sales COGS Forecasted.xlsx" to show forecasting in Excel, and '
                        '"Forecast Sales COGS Simple.ipynb" for forecasting in Python. "Sales COGS.xlsx" '
                        'contains the source data'
                    ],
                    title='Forecasting Simple Time-Series in both Excel and Python',
                    block_title='Example for Simple Time-Series Forecasting'
                ),
                simple_ts_exercise.presentation_frames(),
                InClassExampleFrame(
                    [
                        'Go to the course site and download "Forecasting Financial Statements.ipynb"',
                        f'We will walk through using {pl.Monospace("finstmt")} to forecast financial statements '
                        'using simple time-series models',
                    ],
                    title='Forecasting Financial Statements with Simple Time-Series in Python',
                    block_title='Use finstmt for Financial Statement Forecasting'
                ),
            ],
            title='Forecasting Simple Time-Series',
            short_title='Simple Forecast'
        ),
        pl.Section(
            [
                lp.TwoColumnGraphicDimRevealFrame(
                    [
                        "Shown to the left is Walmart's quarterly sales",
                        'You can see that a plain trend line is never going to accurately forecast these values',
                        'Advanced time-series models can capture these characteristics easily, and many more patterns'
                    ],
                    graphics=[
                        images_path('time-series-plot.png')
                    ],
                    graphics_on_right=False,
                    title='Why Does it get so Complicated?'
                ),
                lp.TwoColumnGraphicDimRevealFrame(
                    [
                        ['There is a distinct', pl.Bold('seasonality'), "to Walmart's quarterly sales"],
                        'The time-series model used to create the plot on the prior slide split the history into '
                        'two parts: a trend component and an annual seasonality component',
                        "Walmart's sales are high at the end of January and neutral for the other quarters",
                        'By plotting components of the time-series model, the analyst can gain a greater understanding '
                        'of the business.'
                    ],
                    graphics=[
                        images_path('time-series-plot-components.png')
                    ],
                    title='Explaining Seasonal Data'
                ),
                lp.DimRevealListFrame(
                    [
                        "So you've determined a trend alone will not fit the historical data. What are next steps?",
                        ['Generally fitting the best time-series model is an involved process which requires '
                         'substantial knowledge of how the models work, see',
                         Hyperlink(
                             'https://www.seanabu.com/2016/03/22/time-series-seasonal-ARIMA-model-in-python/',
                             'this blog post'
                         ), 'for details'],
                        ['An easier version is to use an OLS regression model with time and dummy variables '
                        'for month of year, etc., we can call this the ', pl.Underline('quarterly seasonal trend model.')],
                        ['The easiest version is to let time-series software, such as',
                         Hyperlink('https://facebook.github.io/prophet/docs/quick_start.html', 'prophet'),
                         'make the choice for you']
                    ],
                    title='Predicting Complex Time-Series'
                ),
                SingleBlockDimRevealListFrame(
                    [
                        [
                            pl.Bold('Fit:'),
                            'Create dummy variables for the quarters, then run an OLS regression with the number '
                            'of time periods as well as the four dummy variables as the $X$ variables'
                        ],
                        [
                            pl.Bold('Predict:'),
                            r'For each $t$ you want to predict, calculate $a + \beta t$ adding the appropriate '
                            r'dummy for the quarter of the period.'
                        ]
                    ],
                    [
                        pl.Equation(str_eq=r'y_t = a + \beta_t t + \beta_{d1} D1 + \beta_{d2} D2 + '
                                           r'\beta_{d3} D3 + \beta_{d4} D4  + \epsilon_t', inline=False)
                    ],
                    title='Using the Quarterly Seasonal Trend Model',
                    block_title='Quarterly Seasonal Trend Model'
                ),
                InClassExampleFrame(
                    [
                        'Go to the course site and download the files in Examples > DCF > Forecasting > Complex',
                        'There should be a Jupyter notebook as well as two Excel files. Place these all in the '
                        'same folder',
                        'We will walk through "Forecasting Quarterly Financial Statements.ipynb" to show forecasting '
                        'in Python using both the Quarterly Seasonal Trend Model and the automated software approach.'
                    ],
                    title='Forecasting Complex Time-Series in Python',
                    block_title='Example for Complex Time-Series Forecasting'
                ),
                complex_ts_exercise.presentation_frames(),
            ],
            title='Forecasting Complex Time-Series',
            short_title='Complex Forecast'
        ),
        pl.Section(
            [
                lp.DimRevealListFrame(
                    [
                        'As mentioned in the intro, we can either directly forecast FCFs, or forecast the financial '
                        'statements, then calculate future FCFs from the future financial statements',
                        "Forecasting FCFs doesn't allow the analyst control over individual "
                        "line items. Therefore it is generally preferred to forecast financial statements.",
                        'If you have a short amount of time to put together the model, it can make sense as it is '
                        'less steps and it requires less knowledge of the company.',
                        'It can also make sense to do a FCF forecast alongside the financial statement forecast, as '
                        'a check on your valuation.'
                    ],
                    title='What to Forecast?'
                ),
                lp.DimRevealListFrame(
                    [
                        'Assuming you are going with forecasting financial statements, you should '
                        'forecast only line items which cannot be calculated from other line items',
                        'For example, sales, COGS, SG&A should be forecasted, not operating profit',
                        'You should set your model up so that these calculatable items are calculated '
                        'in the historicals, then carry that through to the forecasted',
                        'Set items as a percentage of other items when it is logical that they should '
                        'scale together. For example, interest expense should be forecasted as a percentage '
                        'of total debt, as if the company takes on more debt, interest expense should increase '
                        'proportionally',
                    ],
                    title='Which Line Items to Forecast?'
                ),
                lp.DimRevealListFrame(
                    [
                        'Despite forecasting line items individually, you must attempt to keep the balance sheet '
                        'balanced in the future',
                        'If your forecast shows assets growing to be much greater than liabilities and equity, '
                        'that implies that the company will need to raise additional funds to finance the '
                        'growth in the assets. Usually increasing debt is the solution.',
                        'If your forecast shows assets lower than liabilities and equity, it means that the profits '
                        'or other sources of funds are not being properly allocated to the assets side. Usually '
                        'increasing cash is the solution',
                    ],
                    title="Don't Be Out of Balance"
                ),
                lp.DimRevealListFrame(
                    [
                        pl.TextSize(-1),
                        'The general process is to run your forecasts, then use another approach to adjust either '
                        'cash or debt to make the balance sheet balance. ',
                        'These adjusted values are called "plugs" because we are "plugging" in whatever makes the '
                        'forecast valid',
                        'To make the adjustment in Excel, calculate the absolute value of the '
                        'difference between assets and liabilities + '
                        'equity, then use goal seek (single year forecast) or solver (multi-year forecast) '
                        'to minimize the value',
                        'In Python, the steps would be similar, only using scipy minimize instead of solver, '
                        'but finstmt handles this automatically for you. When you run a forecast, it will balance '
                        'the balance sheet without any further action from you. You can change how accurate it '
                        'is by setting bs_diff_max and you can change which line items are used as plugs '
                        'in the forecast config',
                    ],
                    title='Balancing the Balance Sheet'
                )
            ],
            title='Forecasting Free Cash Flows',
            short_title='Future FCFs'
        ),
        pl.Section(
            [
                lp.DimRevealListFrame(
                    [
                        'As mentioned in the intro to the DCF model, we can value any asset by taking the present value '
                        'of future cash flows',
                        'These forecasted FCFs represent the future cash flows for the company',
                        'But we have a limited forecast period, beyond which forecasts are getting too innaccurate, '
                        'typically 5 years at most. So what happens after 5 years? The company will probably still be '
                        'earning FCFs in the future.',
                        ['We can calculate a', pl.Bold('terminal value'), 'for the company, which is an estimate of '
                         'how much the company would be sold for if it was sold at the end of the forecast period. '
                         'In other words, it is the future predicted enterprise value.']
                    ],
                    title='What we use FCFs For'
                ),
                lp.DimRevealListFrame(
                    [
                        'The terminal value is an enterprise value at the end of the forecast period. But the bulk of '
                        'the DCF model is getting to an enterprise value, so we have to use a different method '
                        'to estimate the terminal value otherwise we would have an infinitely nested DCF model that could '
                        'never be solved.',
                        ['The two common methods for estimating the terminal value in a DCF model are',
                         pl.Underline('exit multiples'), 'and', pl.Underline('perpetuity growth')],
                        'The exit multiple method uses current values of valuation ratios and applies them to the '
                        'future financials',
                        'The perpetuity growth method assumes that the FCFs will grow at a constant rate after the '
                        'final forecast period.'
                    ],
                    title='How to Get the Terminal Value'
                ),
                lp.DimRevealListFrame(
                    [
                        'There are typically publicly available valuation ratios for public companies such as EV/EBIT, '
                        'EV/EBITDA, EV/Sales, EV/FCF, and P/E',
                        'The idea behind this approach is to use those ratios applied to your final period projected '
                        'financials.',
                        'Each ratio will yield a different terminal value, leading to a different final stock price '
                        'in your model. It is typical to report results with the different measures to get a range.',
                        'For all the EV ratios, multiply the statement item by the ratio to get the EV, then adjust the '
                        'EV using final forecasted values to get the equity value and stock price',
                        'For P/E, calculate final period earnings per share and multiply by the ratio to get the '
                        'stock price'
                    ],
                    title='Finding the Terminal Value via Exit Multiples'
                ),
                lp.DimRevealListFrame(
                    [
                        'The perpetuity growth model follows the same mathematics as the dividend discount model',
                        "We just assume that the last period's FCF continues to grow at some terminal growth rate "
                        "which we set.",
                        pl.Equation(str_eq=r'TV = \frac{FCF (1 + g)}{WACC - g}'),
                        ['The stock price is', pl.Underline('highly'), 'sensitive to the choice of terminal growth '
                         'rate, so there should absolutely be sensitivity analysis and Monte Carlo simulations varying '
                         'it'],
                        'Typical terminal growth rates are around 3%, approximately GDP growth rate'
                    ],
                    title='Finding the Terminal Value via Perpetuity Growth'
                ),
                lp.DimRevealListFrame(
                    [
                        'The last step to get the current enterprise value is to combine the FCFs with the TV',
                        'The TV cash flow should come in the final forecast period, such that the final cash flow '
                        'is $FCF + TV$',
                        'Take the NPV of the cash flows, including the TV',
                        'Follow the adjustments described in the intro lecture to get the stock price from that'
                    ],
                    title='Finding EV Using TV and FCFs'
                ),
                pl.TextSize(-2),
                tv_exercise.presentation_frames(),
                pl.TextSize(0)
            ],
            title='Using the Forecasted FCFs in the DCF Model',
            short_title='Valuation'
        ),

        pl.PresentationAppendix(
            [
                lecture.pyexlatex_resources_frame,
                fcf_exercise.appendix_frames(),
                simple_ts_exercise.appendix_frames(),
                complex_ts_exercise.appendix_frames(),
                tv_exercise.appendix_frames(),
            ]
        )
    ]
def get_content():
    random.seed(1000)

    lecture = get_probability_lecture()
    scenario_excel_lab = get_scenario_analysis_excel_lab_lecture().to_pyexlatex()
    scenario_python_lab = get_scenario_analysis_python_lab_lecture().to_pyexlatex()
    randomness_excel_lab = get_randomness_excel_lab_lecture().to_pyexlatex()
    randomness_python_lab = get_randomness_python_lab_lecture().to_pyexlatex()
    random_stock_lab = get_random_stock_model_lab_lecture().to_pyexlatex()
    full_model_internal_randomness_lab = get_extend_model_internal_randomness_lab_lecture().to_pyexlatex()
    appendix_frames = [
        lecture.pyexlatex_resources_frame,
        scenario_excel_lab.appendix_frames(),
        scenario_python_lab.appendix_frames(),
        randomness_excel_lab.appendix_frames(),
        randomness_python_lab.appendix_frames(),
        random_stock_lab.appendix_frames(),
        full_model_internal_randomness_lab.appendix_frames(),
    ]

    df_mono = pl.Monospace('DataFrame')
    next_slide = lp.Overlay([lp.NextWithIncrement()])
    with_previous = lp.Overlay([lp.NextWithoutIncrement()])
    rand_mono = pl.Monospace('=RAND')
    rand_between_mono = pl.Monospace('=RANDBETWEEN')
    norm_inv_mono = pl.Monospace('=NORM.INV')
    excel_random_normal_example = pl.Monospace('=NORM.INV(RAND(), 10, 1)')
    random_module_mono = pl.Monospace('random')
    py_rand_mono = pl.Monospace('random.random')
    py_rand_uniform_mono = pl.Monospace('random.uniform')
    py_rand_norm_mono = pl.Monospace('random.normalvariate')
    py_random_link = Hyperlink('https://docs.python.org/3.7/library/random.html#real-valued-distributions',
                               '(and other distributions)')
    py_random_normal_example = pl.Monospace('random.normalvariate(10, 1)')
    random_seed_example = pl.Monospace('random.seed(0)')
    next_slide = lp.Overlay([lp.NextWithIncrement()])
    n_iter = pl.Equation(str_eq='n_{iter}')
    df_mono = pl.Monospace('DataFrame')
    df_std = pl.Monospace('df.std()')
    df_mean = pl.Monospace('df.mean()')
    random_choices_mono = pl.Monospace('random.choices')
    random_choices_example = pl.Monospace("random.choices(['Recession', 'Normal', 'Expansion'], [0.3, 0.5, 0.2])")

    return [
        pl.Section(
            [
                lp.TwoColumnGraphicDimRevealFrame(
                    [
                        'So far everything in our models has been deterministic',
                        'Further, we have not explored any scenarios in our models, we have taken the base case as '
                        'the only case',
                        'Unfortunately, the real world is very random. Many possible scenarios could occur.'
                    ],
                    [
                        images_path('dice.jpg'),
                    ],
                    title='Why Model Probability'
                ),
                lp.DimRevealListFrame(
                    [
                        'There are a few ways we can gain a richer understanding of the modeled situation by '
                        'incorporating probability',
                        f'The simplest is {pl.Bold("scenario modeling")}, in which different situations are defined with probabilities, '
                        'and the result of the model is the expected value across the cases.',
                        ['Another is', pl.Bold('internal randomness'),
                         'where randomness is incorporated directly within '
                         'the model logic'],
                        ['Finally,', pl.Bold("Monte Carlo simulation"),
                         'treats the model as deterministic but externally varies the '
                         'inputs to get a distribution of outputs.']
                    ],
                    title='How to Bring Probability In'
                ),
            ],
            title='Motivation for Probability Modeling',
            short_title='Intro',
        ),
        pl.Section(
            [
                lp.Frame(
                    [
                        pl.UnorderedList([
                            lp.DimAndRevealListItems([
                                ['When something is measured numerically, it can be either a', pl.Bold('discrete'),
                                 'variable, or a', pl.Bold('continuous'), 'variable.'],

                            ])
                        ]),
                        lp.Block(
                            [
                                pl.Equation(str_eq=r'x \in \{x_1, x_2, ... x_n\}', inline=False),
                                pl.VSpace(-0.4),
                                pl.UnorderedList([
                                    [pl.Equation(str_eq=r'\{x_1, x_2, ... x_n\}:'), 'A specific set of values'],
                                ])
                            ],
                            title='Discrete Variables'
                        ),
                        lp.Block(
                            [
                                pl.Equation(str_eq=r'x \in \mathbb{R} \text{ or } [a, b]', inline=False),
                                pl.VSpace(-0.4),
                                pl.UnorderedList([
                                    [pl.Equation(str_eq='\mathbb{R}:'), 'All real numbers'],
                                    [pl.Equation(str_eq='[a, b]:'), 'Some interval between two values or infinity'],

                                ])
                            ],
                            title='Continuous Variables'
                        ),
                    ],
                    title='Math Review: Discrete and Continuous Variables'
                ),
                lp.Frame(
                    [
                        pl.TextSize(-3),
                        pl.UnorderedList([
                            lp.DimAndRevealListItems([
                                [pl.Bold('Expected value'), 'is the average outcome over repeated trials'],
                                "It is generally useful to get a single output from multiple possible cases",
                            ], dim_earlier_items=False)
                        ]),
                        lp.Block(
                            [
                                pl.Equation(str_eq=r'E[x] = \sum_{i=1}^{N} p_i x_i', inline=False),
                                pl.VSpace(-0.4),
                                pl.UnorderedList([
                                    [pl.Equation(str_eq=r'E[x]:'), 'Expected value for', pl.Equation(str_eq='x')],
                                    [pl.Equation(str_eq=r'x_i:'), 'A specific value for', pl.Equation(str_eq='x')],
                                    [pl.Equation(str_eq=r'p_i:'), 'The probability associated with value',
                                     pl.Equation(str_eq='x_i')],
                                    [pl.Equation(str_eq=r'N:'), 'The total number of possible values of',
                                     pl.Equation(str_eq='x')],
                                ])
                            ],
                            title='Discrete Variables'
                        ),
                        lp.Block(
                            [
                                pl.Equation(str_eq=r'E[x] = \frac{1}{N} \sum_{i=1}^{N} x_i', inline=False),
                                pl.VSpace(-0.4),
                                pl.UnorderedList([
                                    [pl.Equation(str_eq=r'N:'), 'The number of samples collected for',
                                     pl.Equation(str_eq='x')],
                                ])
                            ],
                            title='Continuous Variables'
                        ),
                    ],
                    title='Math Review: Expected Value'
                ),
                lp.GraphicFrame(
                    images_path('different-variance-plot.pdf'),
                    title='Math Review: Variance in One Picture'
                ),
                lp.Frame(
                    [
                        pl.TextSize(-2),
                        pl.UnorderedList([
                            lp.DimAndRevealListItems([
                                [pl.Bold('Variance'), 'and', pl.Bold('standard deviation'),
                                 'are measures of the dispersion '
                                 'of values of a random variable.'],
                                'Variance is the real quantity of interest, but standard deviation is easier to understand '
                                'because it has the same units as the variable, while variance has units squared'
                            ], dim_earlier_items=False),
                        ]),
                        lp.Block(
                            [
                                EquationWithVariableDefinitions(
                                    r'Var[x] = \sigma^2 = \frac{1}{N - 1} \sum_{i=1}^{N} (x_i - \mu)^2',
                                    [
                                        [pl.Equation(str_eq=r'N:'), 'Number of samples of', pl.Equation(str_eq=r'x')],
                                        [pl.Equation(str_eq=r'\mu:'), 'Sample mean'],
                                    ]
                                ),
                            ],
                            title='Variance of a Continuous Variable'
                        ),
                        lp.Block(
                            [
                                EquationWithVariableDefinitions(
                                    r'\sigma = \sqrt{Var[x]}',
                                    [
                                        [pl.Equation(str_eq=r'\sigma:'), 'Standard deviation'],
                                    ],
                                    space_adjustment=-0.5
                                ),
                            ],
                            title='Standard Deviation'
                        ),
                    ],
                    title='Math Review: Variance and Standard Deviation'
                ),
                lp.TwoColumnGraphicDimRevealFrame(
                    [
                        ['A', pl.Bold('probability distribution'),
                         'represents the probabilities of different values of '
                         'a variable'],
                        'For discrete variables, this is simply a mapping of possible values to probabilities, e.g. for a coin '
                        'toss, heads = 50% and tails = 50%',
                        'For continuous variables, a continuous distribution is needed, such as the normal distribution',
                    ],
                    graphics=[
                        images_path('normal-distribution.png'),
                    ],
                    title='Math Review: Probability Distributions'
                ),
                lp.TwoColumnGraphicDimRevealFrame(
                    [
                        pl.TextSize(-2),
                        ["You've probably heard of the", pl.Bold('normal distribution'),
                         'as it is very commonly used because it occurs a lot in nature'],
                        ['It is so common because of the', pl.Bold('central limit theorem'), 'which says that '
                                                                                             'averages of variables will follow a normal distribution, regardless of the distribution of the '
                                                                                             'variable itself'],
                        'This has many applications. For example, we can view the investment rate as an average across '
                        'individual investment returns, and so it will be normally distributed.',
                    ],
                    graphics=[
                        images_path('normal-distribution-percentages.png'),
                    ],
                    title='Math Review: Normal Distribution'
                ),
                lp.Frame(
                    [
                        pl.TextSize(-3),
                        pl.UnorderedList([
                            lp.DimAndRevealListItems([
                                'We want to extend our retirement model to say that the investment return is not constant.',
                                'We can treat the interest rate as either a discrete (specific values) or a continuous '
                                '(range of values, more realistic) variable'
                            ], dim_earlier_items=False),

                        ]),
                        lp.Block(
                            [
                                pl.Center(
                                    [
                                        lt.Tabular(
                                            [
                                                lt.ValuesTable.from_list_of_lists([
                                                    ['Interest Rate', 'Probability']
                                                ]),
                                                lt.MidRule(),
                                                lt.ValuesTable.from_list_of_lists([
                                                    ['2%', '30%'],
                                                    ['5%', '50%'],
                                                    ['7%', '20%'],
                                                ]),
                                            ],
                                            align='cc'
                                        )
                                    ]
                                )
                            ],
                            title='As a Discrete Variable'
                        ),
                        lp.Block(
                            [
                                pl.Equation(str_eq=r'r_i \sim N(\mu, \sigma^2)', inline=False),
                                pl.VSpace(-0.5),
                                pl.UnorderedList([
                                    [pl.Equation(str_eq=r'N:'), 'Normal distribution'],
                                    [pl.Equation(str_eq=r'\mu:'), 'Interest rate mean'],
                                    [pl.Equation(str_eq=r'\sigma:'), 'Interest rate standard deviation'],
                                ])
                            ],
                            title='As a Continuous Variable'
                        ),
                    ],
                    title='A Non-Constant Interest Rate'
                ),
            ],
            title='Mathematical Tools for Probability Modeling',
            short_title='Math Review'
        ),
        pl.Section(
            [
                lp.Frame(
                    [
                        pl.TextSize(-1),
                        lp.Block(
                            [
                                pl.Center(
                                    [
                                        lt.Tabular(
                                            [
                                                lt.ValuesTable.from_list_of_lists([
                                                    ['State of Economy', 'Interest Rate', 'Savings Rate', 'Probability']
                                                ]),
                                                lt.MidRule(),
                                                lt.ValuesTable.from_list_of_lists([
                                                    ['Recession', '2%', '35%', '30%'],
                                                    ['Normal', '5%', '30%', '50%'],
                                                    ['Expansion', '7%', '25%', '20%'],
                                                ]),
                                            ],
                                            align='l|ccc'
                                        )
                                    ]
                                )
                            ],
                            title='Interest Rate Scenarios'
                        ),
                        pl.UnorderedList([
                            lp.DimAndRevealListItems([
                                ['In scenario modeling, different cases for model parameters are chosen. Several '
                                 'parameters may be altered at once in a given case.'],
                                "Here we are making the different cases the state of the economy. When the economy is doing "
                                "poorly, the individual earns a lower return, but also saves more because they don't want to "
                                "overspend at a bad time",
                                "When the economy does well, the individual earns a higher return, but also spends more"
                            ])
                        ]),
                    ],
                    title='Scenario Modeling'
                ),
                lp.DimRevealListFrame(
                    [
                        ['We can implement scenario modeling', pl.Bold('internal'), 'or', pl.Bold('external'),
                         'to our model'],
                        ['With an internal implementation, the cases are built', pl.Underline('into the model logic'),
                         'itself, '
                         'and model logic also takes the expected value of the case outputs. The inputs of the model',
                         'are now the cases and probabilities.'],
                        ['With an external implementation, the', pl.Underline('model logic is left unchanged,'),
                         'instead the '
                         'model is run separately with each case, then the expected value is calculated across the outputs '
                         'from the multiple model runs.'],
                    ],
                    title='Implementing Scenario Modeling'
                ),
                lp.Frame(
                    [
                        pl.Center(
                            [
                                lt.Tabular(
                                    [
                                        lt.ValuesTable.from_list_of_lists([
                                            [pl.Bold('Internal'), pl.Bold('External')]
                                        ]),
                                        lt.MidRule(),
                                        lt.MidRule(),
                                        lt.ValuesTable.from_list_of_lists([
                                            ['Original model is now an old version',
                                             'Original model can still be used normally'],
                                        ]),
                                        # TODO [#14]: each row should come one per slide, but need to allow overlays in lt items
                                        lt.MidRule(),
                                        lt.ValuesTable.from_list_of_lists([
                                            ['Model runs exactly as before',
                                             'Getting full results of model requires running the model multiple times and '
                                             'aggregating output']
                                        ]),
                                        lt.MidRule(),
                                        lt.ValuesTable.from_list_of_lists([
                                            ['Model complexity has increased', 'Model complexity unchanged']
                                        ]),
                                        lt.MidRule(),
                                        lt.ValuesTable.from_list_of_lists([
                                            ['Complexity to run model is unchanged',
                                             'Complexity to run model has increased']
                                        ]),
                                    ],
                                    align='L{5cm}|R{5cm}'
                                )
                            ]
                        )
                    ],
                    title='Internal or External Scenario Analysis?'
                ),
                lp.DimRevealListFrame(
                    [
                        'For internal scenario analysis, set up a table of the cases and probabilities. Then calculate the '
                        'expected value of these cases for each model parameter. Then use the expected value as the new '
                        'model parameter.',
                        'For external scenario analysis, a data table is useful. Create the data table of outputs for each case '
                        'and another table of case probabilities, then combine them to produce the expected value of '
                        'the output.',
                        'If you are trying to change more than two inputs at once in external scenario '
                        'analysis, this becomes more '
                        'challenging but you can assign a number to each set of inputs and have the model look up the '
                        'inputs based on the case number, using the case number as the data table input.'

                    ],
                    title='Scenario Analysis in Excel'
                ),
                InClassExampleFrame(
                    [
                        'I will now go through adding external scenario analysis to the Dynamic Salary Retirement Model '
                        'in Excel',
                        'The completed exercise on the course site as "Dynamic Salary Retirement Model Sensitivity.xlsx"',
                    ],
                    title='Scenario Analysis in Excel',
                    block_title='Adding Scenario Analysis to the Dynamic Retirement Excel Model'
                ),
                scenario_excel_lab.presentation_frames(),
                lp.DimRevealListFrame(
                    [
                        ['For internal scenario analysis, set up a', df_mono,
                         'or dictionary of the cases and probabilities. Then calculate '
                         'the expected value of these cases for each model parameter. Then use the expected value as the new '
                         'model parameter.'],
                        'For external scenario analysis, just call your model function with each input case, collect the '
                        'results, and combine them to produce the expected value of the output.'
                    ],
                    title='Scenario Analysis in Python'
                ),
                InClassExampleFrame(
                    [
                        'I will now go through adding external scenario analysis to the Dynamic Salary Retirement Model '
                        'in Python',
                        'he completed exercise on the course site as "Dynamic Salary Retirement Model Scenario.ipynb"',
                    ],
                    title='Scenario Analysis in Python',
                    block_title='Adding Scenario Analysis to the Dynamic Retirement Python Model'
                ),
                scenario_python_lab.presentation_frames(),
            ],
            title='Scenario Modeling'
        ),
        pl.Section(
            [
                lp.DimRevealListFrame(
                    [
                        ["Using the technique of", pl.Bold('internal randomness,'),
                         'something random is added internally to the model'],
                        'Instead of taking a fixed input, random values for that variable are drawn',
                        'This technique can be used with both discrete and continuous variables'
                    ],
                    title='What is Internal Randomness?'
                ),
                lp.GraphicFrame(
                    internal_randomness_graphic(),
                    title='Internal Randomness in One Picture'
                ),
                lp.DimRevealListFrame(
                    [
                        'Internal randomness makes sense when the random behavior is integral to your model',
                        'If you are just trying to see how changing inputs affects outputs, or trying to get confidence intervals for outputs, '
                        'an external method such as sensitivity analysis or Monte Carlo simulation would make more sense.',
                        'For example, if we want to allow investment returns to vary in our retirement model, an external method fits well because '
                        'the core model itself is deterministic',
                        'If instead we were modeling a portfolio, we might use internal randomness to get the returns for each asset.'
                    ],
                    title='Should I Use Internal Randomness?'
                ),
                lp.DimRevealListFrame(
                    [
                        'Similarly to our discussion of internal vs. external sensitivity analysis, internal randomness keeps '
                        'operational complexity (how to run the model) low, but increases model complexity.',
                        'The main drawback of internal randomness is that the same set of inputs will give different outputs each time the model is run',
                        'While this is the desired behavior, it can make it difficult to determine whether everything is working.'
                    ],
                    title='Internal Randomness Advantages and Pitfalls'
                ),
                lp.TwoColumnGraphicDimRevealFrame(
                    [
                        'Instead of taking the input as fixed, draw it from a distribution',
                        'We need to define a distribution for each input we want to randomize. This will typically be a normal distribution, and then '
                        'we just need to give it a reasonable mean and standard deviation',
                        'Put the most reasonable or usual value as the mean. Then think about the probabilities of the normal distribution relative '
                        'to standard deviation to set it'
                    ],
                    graphics=[
                        images_path('normal-distribution-percentages.png'),
                    ],
                    title='Internal Randomness with Continuous Variables'
                ),
                lp.DimRevealListFrame(
                    [
                        ['The main functions for randomness in Excel are', rand_mono, 'and', rand_between_mono],
                        'The latter gives a random number between two numbers, while the former gives a random number '
                        'between 0 and 1. Both of these draw from a uniform distribution (every number equally likely)',
                        ['Meanwhile, the', norm_inv_mono,
                         'function gives the value for a certain normal distribution at a certain probability (it is not random)'],
                        'We can combine these two functions to draw random numbers from a normal distribution',
                        [excel_random_normal_example,
                         'would draw a number from a normal distribution with mean 10 and standard deviation 1'],
                    ],
                    title='Internal Randomness with Continuous Variables in Excel'
                ),
                InClassExampleFrame(
                    [
                        'I will now go through generating random continuous variables '
                        'in Excel',
                        'The completed exercise on the course site is called "Generating Random Numbers.xlsx"',
                        'We will focus only on the "Continuous" sheet for now',
                    ],
                    title='Example for Continuous Random Variables in Excel',
                    block_title='Generating Random Numbers from Normal Distributions in Excel'
                ),
                randomness_excel_lab.presentation_frames(),
                lp.DimRevealListFrame(
                    [
                        ['In Python, we have the built-in', random_module_mono, 'module'],
                        ['It has functions analagous to those in Excel:', py_rand_mono, 'works like', rand_mono,
                         'and', py_rand_uniform_mono, 'works like', rand_between_mono],
                        ['Drawing numbers from a normal distribution', py_random_link, 'is easier: just one function',
                         py_rand_norm_mono],
                        [py_random_normal_example,
                         'would draw a number from a normal distribution with mean 10 and standard deviation 1']
                    ],
                    title='Internal Randomness with Continuous Variables in Python'
                ),
                InClassExampleFrame(
                    [
                        'I will now go through generating random continuous variables '
                        'in Python',
                        'The completed exercise on the course site is called "Generating Random Numbers.ipynb"',
                        'We will focus only on the "Continuous" section for now',
                    ],
                    title='Example for Continuous Random Variables in Python',
                    block_title='Generating Random Numbers from Normal Distributions in Python'
                ),
                randomness_python_lab.presentation_frames(),
                lp.DimRevealListFrame(
                    [
                        'We can also build randomness into the model for discrete variables',
                        "With discrete variables, our distribution is just a table of probabilities for the different values",
                        'To pick a random value for a discrete variable, first add another column to your table which has the '
                        'cumulative sum of the prior probabilties, and then another column which is that column plus the '
                        'current probability',
                        'Then generate a random number between 0 and 1 from a uniform distribution',
                        'If the generated number is between the probability and the cumulative sum of prior probabilities, choose that case'
                    ],
                    title='Internal Randomness with Discrete Variables'
                ),
                lp.Frame(
                    [
                        pl.TextSize(-1),
                        lp.Block(
                            [
                                pl.Center(
                                    [
                                        lt.Tabular(
                                            [
                                                lt.ValuesTable.from_list_of_lists([
                                                    ['State of Economy', 'Interest Rate', 'Probability', 'Begin Range',
                                                     'End Range']
                                                ]),
                                                lt.MidRule(),
                                                lt.ValuesTable.from_list_of_lists([
                                                    ['Recession', '2%', '30%', '0%', '30%'],
                                                    ['Normal', '5%', '50%', '30%', '80%'],
                                                    ['Expansion', '7%', '20%', '80%', '100%'],
                                                ]),
                                            ],
                                            align='L{2cm}|cccc'
                                        )
                                    ]
                                )
                            ],
                            title='Interest Rate Scenarios'
                        ),
                        pl.UnorderedList([
                            pl.TextSize(-2),
                            lp.DimAndRevealListItems([
                                'The Begin Range column is calculated as the cumulative sum of prior probabilities',
                                'The End Range column is calculated as Begin Range + Probability',
                                "Generate a random number between 0 and 1. If it is between the begin and end range, "
                                "that is the selected value",
                                "If it's 0.15, it's a recession. If it's 0.45, it's a normal period. If it's 0.94, it's "
                                "an expansion period."
                            ], vertical_fill=True)
                        ]),
                    ],
                    title='An Example of Internal Randomness with Discrete Variables'
                ),
                lp.DimRevealListFrame(
                    [
                        'The steps in the preceeding slides need to be carried out manually in Excel',
                        ['In Python, there is a built-in function which is doing all of this in the background,',
                         random_choices_mono],
                        ['Simply do', random_choices_example, 'to yield the exact same result for the prior example']
                    ],
                    title='Random Discrete Variables in Python'
                ),
                InClassExampleFrame(
                    [
                        'I will now go through generating random discrete variables '
                        'in both Excel and Python',
                        'We will be continuing with the same Excel workbook and Jupyter notebook from before, '
                        '"Generating Random Numbers.xlsx" and "Generating Random Numbers.ipynb"',
                        'We will focus only on the "Discrete" sheet/section now',
                    ],
                    title='Example for Discrete Random Variables in Excel and Python',
                    block_title='Generating Random Numbers from Discrete Distributions in Excel and Python'
                ),
                random_stock_lab.presentation_frames(),
                InClassExampleFrame(
                    [
                        'I will now add internal randomness with discrete variables to '
                        'both the Excel and Python Dynamic Salary Retirement models to simulate economic conditions '
                        'changing year by year',
                        'The completed models on the course site are called '
                        '"Dynamic Salary Retirement Model Internal Randomness.xlsx" and '
                        '"Dynamic Salary Retirement Model Internal Randomness.ipynb"',
                    ],
                    title='Adding Internal Randomness to Excel and Python Models',
                    block_title='Extending the Dynamic Salary Retirement Model with Internal Randomness'
                ),
                full_model_internal_randomness_lab.presentation_frames(),
            ],
            title='Internal Randomness'
        ),
        pl.PresentationAppendix(appendix_frames),
    ]
Ejemplo n.º 5
0
def get_content():
    lecture = get_advanced_modeling_lecture()

    pd_mono = pl.Monospace('pandas')
    selenium_mono = pl.Monospace('selenium')
    requests_mono = pl.Monospace('requests')
    matplotlib_mono = pl.Monospace('matplotlib')
    holoviews_mono = pl.Monospace('holoviews')
    open_mono = pl.Monospace('open')
    os_mono = pl.Monospace('os')
    shutil_mono = pl.Monospace('shutil')
    pathlib_mono = pl.Monospace('pathlib')
    git_mono = pl.Monospace('git')
    sqlalchemy_mono = pl.Monospace('SQLAlchemy')
    fin_model_types = {
        'Portfolio valuation and optimization': 'Find the returns, value, and risk of a portfolio and select the best '
                                                'asset allocation for the portfolio',
        'Additional Funds Needed (AFN)': 'Budgeting model which uses forecasted financial statements to determine '
                                         'how much capital should be raised',
        'Lease or Own': 'Guides the decision of whether to rent or buy an asset',
        'Event Studies': 'Tries to determine the impact of an event',
        'Merger and Aquisition (M&A)': 'A DCF valuation of a target company with operations being combined '
                                       'with the parent at a merger date. Detetermines M&A price.',
        'Leveraged Buyout (LBO)': 'A specialized M&A model used for when large amounts of debt are being used '
                                  'to purchase the target firm.',
        'Derivatives Valuation': 'Value options, swaps, forwards, etc.',
        'Debt models': 'Immunization models are about having the right amount of cash in the future, term structure '
                       'models estimate the rates for different maturity bonds, and default-adjusted return models '
                       'factor in default in determining debt returns',
        'Value at Risk (VaR)': 'Determine how much an investment might lose with a certain probability in a certain '
                               'time span',
    }
    fin_model_items = [f'{pl.Underline(key)}: {value}' for key, value in fin_model_types.items()]

    return [
        pl.Section(
            [
                lp.DimRevealListFrame(
                    [
                        pl.TextSize(-1),
                        'Throughout the Financial Modeling with Python and Excel course, '
                        'we have covered Python and Excel basics',
                        'We have also covered financial modeling specifics, such as how to structure a '
                        'financial model in both Python and Excel, cash flow and probability modeling, '
                        'sensitivity analysis, scenario analysis, and Monte Carlo simulations',
                        'As far as types of financial models, we covered a retirement model, a '
                        'capital budgeting model, a lender profitability model, and the discounted '
                        'cash flow (DCF) valuation of a stock',
                        "There is a lot I didn't cover in that course. Let's "
                        "do a quick overview of it today.",
                        "This will serve as a roadmap to learn additional topics after completing the "
                        "first course. This is also the beginning of a new "
                        "Advanced Financial Modeling with Python course"
                    ],
                    title='What we Covered and What is Left'
                )
            ],
            title='Introduction'
        ),
        pl.Section(
            [
                lp.DimRevealListFrame(
                    fin_model_items[:5],
                    title='Financial Models 1'
                ),
                lp.DimRevealListFrame(
                    fin_model_items[5:9],
                    title='Financial Models 2'
                ),
                lp.DimRevealListFrame(
                    [
                        'Here are some links with free resources to learn more about types of models',
                        'The following examples will be using Excel only',
                        Hyperlink('http://macabacus.com/learn', 'Macabacus'),
                        Hyperlink(
                            'https://corporatefinanceinstitute.com/resources/knowledge/modeling/',
                            'Corporate Finance Institute'
                        ),
                        Hyperlink('https://fminstitute.com/learning/', 'Financial Modeling Institute'),
                        'And I found a couple Python resources, though the coding standards are not great:',
                        Hyperlink('http://www.financeandpython.com/Finance.html', 'Finance and Python'),
                        Hyperlink(
                            'https://www.datacamp.com/community/tutorials/finance-python-trading',
                            'Build a Trading Algorithm in Python',
                        )
                    ],
                    title='Financial Model Resources'
                )
            ],
            title='Types of Financial Models'
        ),
        pl.Section(
            [
                lp.TwoColumnGraphicDimRevealFrame(
                    [
                        'Data pipelines are about getting the input data into your model in a '
                        'standardized way',
                        'Within data pipelines, there are two main steps: data collection and '
                        'data wrangling (cleaning + reformatting).',
                        'Either step can be automated, ideally both would be, but it always comes down '
                        'to a tradeoff with modeler time'
                    ],
                    graphics=[
                        images_path('data-pipeline.png')
                    ]
                ),
                lp.DimRevealListFrame(
                    [
                        pl.TextSize(-1),
                        'Data can come from many sources, but most typically it originates from the Internet',
                        'If you can manually download the data, you can automate it via web scraping',
                        'You can also extract different types of data with web scraping, even if it is not structured '
                        'as a dataset',
                        'Some data comes from an API, where you need to send requests to download the data',
                        [selenium_mono, 'uses Python code to drive a browser such as Chrome while', requests_mono,
                         'is a more lightweight, text based way to make web requests (good for APIs).'],
                        ['Another common source of data is SQL databases. While you will still need to have a basic '
                         'understanding of SQL to query them, Python can help with', sqlalchemy_mono, 'which allows',
                         'you to write the queries in Python.', pd_mono, 'also has functionality to work with SQL']
                    ],
                    title='Data Collection'
                ),
                lp.DimRevealListFrame(
                    [
                        pl.TextSize(-1),
                        ['We have already covered the best general-purpose tool for wrangling data:', pd_mono],
                        'We did not cover it in enough detail to cover all data cleaning cases',
                        'The main material left is selecting, merging, grouping, and reshaping',
                        'Even if your data is without issues, you may still need to change the format, combine '
                        'sources, aggregate, etc.',
                        'Regular expressions are a way of matching any possible string and extracting parts of '
                        'it, which useful for messy data',
                    ],
                    title='Data Wrangling'
                ),
                lp.DimRevealListFrame(
                    [
                        Hyperlink(
                            'https://stackabuse.com/getting-started-with-selenium-and-python/',
                            'Get Started Browser-Based Web Scraping with Selenium'
                        ),
                        Hyperlink(
                            'https://github.com/mherrmann/selenium-python-helium',
                            'Helium - A Higher-Level API to Selenium'
                        ),
                        Hyperlink(
                            'https://realpython.com/python-requests/',
                            'Get Started Text-Based Web Scraping with Requests'
                        ),
                        Hyperlink(
                            'https://pandas.pydata.org/pandas-docs/stable/getting_started/10min.html',
                            'Pandas Intro, Covers Basics of Needed Topics'
                        ),
                        Hyperlink(
                            'https://pandas.pydata.org/pandas-docs/stable/user_guide/cookbook.html#cookbook',
                            'Advanced Pandas'
                        ),
                        Hyperlink(
                            'https://scotch.io/tutorials/an-introduction-to-regex-in-python',
                            'Intro to Regular Expressions'
                        ),
                        Hyperlink(
                            'https://docs.python.org/3/library/re.html',
                            'Regular Expression Reference'
                        ),
                        Hyperlink(
                            'https://auth0.com/blog/sqlalchemy-orm-tutorial-for-python-developers/',
                            'SQLAlchemy Overview Tutorial'
                        ),
                        Hyperlink(
                            'https://towardsdatascience.com/sqlalchemy-python-tutorial-79a577141a91',
                            'SQLAlchemy Simple Tutorial and Examples'
                        ),
                        Hyperlink(
                            'https://docs.sqlalchemy.org/en/13/intro.html',
                            'SQLAlchemy Documentation'
                        ),
                    ],
                    title='Data Pipelines Resources',

                )
            ],
            title='Data Pipelines'
        ),
        pl.Section(
            [
                lp.TwoColumnGraphicDimRevealFrame(
                    [
                        'We covered basic mathematical tools including basic probability theory, '
                        'algebra, variance/standard deviation, averages, and basic regressions',
                        'Most financial modeling does not take very advanced math, with the exception '
                        'of some derivatives models',
                        "But there are a few more useful tools we didn't have time to cover"
                    ],
                    graphics=[
                        images_path('equations-chalkboard-2.jpg')
                    ],
                    title='What Math we Covered'
                ),
                lp.DimRevealListFrame(
                    [
                        ['Often we want to maximize or minimize something, e.g. maximize returns or NPV, '
                         'minimize risk. We can do this in general with a mathematical technique called',
                         pl.Underline('optimization')],
                        ['If you have a complicated custom model, such that the algebra is getting too difficult '
                        'to do by hand, you can use a', pl.Underline('computer algebra system')],
                        [pl.Underline('Levenshtein (edit) distance'), 'can be used to say how similar two strings are,',
                         'which is useful for data cleaning and more.']
                    ],
                    title='General Math Tools'
                ),
                lp.DimRevealListFrame(
                    [
                        'We covered Ordinary Least Squares (OLS) regressions, which is what anyone means if they '
                        'just say regression',
                        ["There are many more kinds of regressions, we can't even mention them all here. "
                         "But most likely to be useful include", pl.Underline('logistic regression'), 'for when',
                         'probabilities are dependent variables and', pl.Underline('panel regression + fixed effects'),
                         'for when you are dealing',
                         'with multiple instruments over time'],
                        'There are many time-series models to cover, as was mentioned in the forecasting lecture',
                        [pl.Underline('Machine learning/AI'), 'can be used to make classifications or predictions']
                    ],
                    title='Statistics Tools'
                ),
                lp.DimRevealListFrame(
                    [
                        Hyperlink(
                            'https://towardsdatascience.com/optimization-with-scipy-and-application-ideas-to-machine-learning-81d39c7938b8',
                            'Optimization with SciPy'
                        ),
                        Hyperlink(
                            'https://docs.sympy.org/latest/tutorial/preliminaries.html',
                            'Computer Algebra with SymPy'
                        ),
                        Hyperlink(
                            'https://www.geeksforgeeks.org/fuzzywuzzy-python-library/',
                            'Levenshtein Distance using fuzzywuzzy'
                        ),
                        Hyperlink(
                            'https://towardsdatascience.com/logistic-regression-python-7c451928efee',
                            'Intro to Logistic Regression in Python'
                        ),
                        Hyperlink(
                            'https://medium.com/pew-research-center-decoded/using-fixed-and-random-effects-models-for-panel-data-in-python-a795865736ab',
                            'Intro to Panel Regression in Python'
                        ),
                        Hyperlink(
                            'https://www.statsmodels.org/stable/py-modindex.html',
                            'Statistical Models in statsmodels'
                        ),
                        Hyperlink(
                            'https://bashtage.github.io/linearmodels/doc/index.html',
                            'More Statistical Models in linearmodels'
                        ),
                        Hyperlink(
                            'https://docs.scipy.org/doc/scipy/reference/stats.html',
                            'More Statistical Tools in Scipy'
                        ),
                        Hyperlink(
                            'https://machinelearningmastery.com/machine-learning-in-python-step-by-step/',
                            'Getting Started with Machine Learning in Python'
                        ),
                        Hyperlink(
                            'https://machinelearningmastery.com/start-here/',
                            'General Introduction to Machine Learning'
                        ),
                        Hyperlink(
                            'https://datacamp.com/community/tutorials/deep-learning-python',
                            'Deep Learning (AI) in Python using Keras'
                        ),
                        Hyperlink(
                            'https://github.com/automl/auto-sklearn/',
                            'Automated Machine Learning with auto-sklearn'
                        ),
                    ],
                    title='Mathematical Tools Resources'
                )
            ],
            title='Mathematical Tools'
        ),
        pl.Section(
            [
                lp.TwoColumnGraphicDimRevealFrame(
                    [
                        "We didn't have very much time to cover presenting the model in Python, other than formatting text",
                        "For Excel, the model is already presented so just structure the workbook well",
                        "A well structured Jupyter notebook or Python script is important for another modeler to "
                        "pick up where you left off. But it still is not an ideal format for non-technical consumers "
                        "of your model"
                    ],
                    graphics=[
                        images_path('example-report.png')
                    ],
                    title='Presenting Model Results'
                ),
                lp.DimRevealListFrame(
                    [
                        "One easy way that doesn't require anything we haven't learned is separating model logic "
                        "and presentation",
                        "Develop as you will while building the model. But when it's time to share the results, "
                        "separate the main model logic (classes and functions) into separate Python file(s)",
                        "Then the Jupyter notebook will just show high-level calls to your model and the results"
                    ],
                    title='Present with Basic Jupyter'
                ),
                lp.DimRevealListFrame(
                    [
                        'Less technical consumers of the model may just want the model conclusions and not '
                        'to actually use the model themselves',
                        'In this case, it is useful to generate reports containing the model results',
                        'There are three major ways to make reports: HTML, LaTeX, and direct PDF solutions',
                        'If all you need is PDF output, a direct solution is fine, but HTML and LaTeX (which '
                        'can be converted to HTML) can both be converted to PDF and have the added advantage of '
                        'being viewable as a web page',
                        'Templating is also easier with HTML and LaTeX'
                    ],
                    title='Create Reports'
                ),
                lp.DimRevealListFrame(
                    [
                        'There is another way for non-technical consumers of your model to interact with it: '
                        'via an app',
                        'It is possible to build apps right in a Jupyter notebook using widgets',
                        'A web app could also be created with a web framework',
                        'With an app, a non-technical consumer of your model can adjust the inputs and see '
                        'the outputs, without having any knowledge of Python or instructions'
                    ],
                    title='Publish Reports and Models'
                ),
                lp.DimRevealListFrame(
                    [
                        ['We covered very basic plots using', pd_mono],
                        [matplotlib_mono, 'provides all the plotting functionality to', pd_mono, 'and any', pd_mono,
                         'plots can be adjusted using', matplotlib_mono, 'options'],
                        'Several libraries exist for interactive plots, which allow for dropdowns, sliders, '
                        'selecting points, zooming, tooltips, and more',
                        ['Other plotting styles are becoming more popular, such as', holoviews_mono + ',', 'in which',
                         'you just describe the data and it can generate interactive plots for you']
                    ],
                    title='Advanced Plotting'
                ),
                lp.DimRevealListFrame(
                    [
                        pl.TextSize(-1),
                        Hyperlink(
                            'https://dev.to/goyder/automatic-reporting-in-python---part-1-from-planning-to-hello-world-32n1',
                            'Intro to Creating HTML Reports in Python',
                        ),
                        Hyperlink(
                            'https://towardsdatascience.com/creating-pdf-reports-with-python-pdfkit-and-jinja2-templates-64a89158fa2d',
                            'Create HTML Reports and Output to PDF',
                        ),
                        Hyperlink(
                            'https://realpython.com/primer-on-jinja-templating/',
                            'Templating HTML and LaTeX Using Jinja'
                        ),
                        Hyperlink(
                            'https://www.reportlab.com/docs/reportlab-userguide.pdf',
                            'Direct PDF Output with Reportlab',
                        ),
                        Hyperlink(
                            'https://nickderobertis.github.io/py-ex-latex/',
                            'Direct to LaTeX Using pyexlatex'
                        ),
                        Hyperlink(
                            'https://www.datacamp.com/community/tutorials/matplotlib-tutorial-python',
                            'Matplotlib Plotting Tutorial'
                        ),
                        Hyperlink(
                            'https://holoviews.org/getting_started/index.html',
                            'Get started with Holoviews'
                        ),
                        Hyperlink(
                            'https://www.youtube.com/watch?v=L91rd1D6XTA&ab_channel=Enthought',
                            'Introduction to Panel for Building Apps in Jupyter'
                        ),
                        Hyperlink(
                            'https://panel.holoviz.org/getting_started/index.html',
                            'Tutorial for Panel'
                        ),
                        Hyperlink(
                            'https://voila.readthedocs.io/en/stable/',
                            'Convert a Jupyter Notebook to a Web App using Voila'
                        ),
                        Hyperlink(
                            'https://voila-gallery.org/services/gallery/',
                            'Examples of Voila Web Apps'
                        ),
                        Hyperlink(
                            'https://scotch.io/tutorials/getting-started-with-flask-a-python-microframework',
                            'Get Started Building Web Apps with Flask'
                        ),
                        Hyperlink(
                            'https://anvil.works/learn/tutorials/jupyter-notebook-to-web-app',
                            'Convert a Jupyter Notebook to a Web App using Anvil'
                        ),
                        Hyperlink(
                            'https://www.fullstackpython.com/',
                            'Full Tutorials for Python Web Development'
                        ),
                    ],
                    title='Presentation Resources'
                )
            ],
            title='Present Results'
        ),
        pl.Section(
            [
                lp.TwoColumnGraphicDimRevealFrame(
                    [
                        'We were only able to cover basic Python, and certainly not a lot of practices that would '
                        'typically be used in programming',
                        'Python is very flexible in that you can be productive in it with very little understanding '
                        'or mastery of it',
                        'But if you do gain a greater knowledge of it, it can unlock new potential.',
                        'Further, there is more we can learn from the software engineering world in how to improve '
                        'our programming'
                    ],
                    graphics=[
                        images_path('python-code-blur.jpeg')
                    ],
                    title='Your Programming Future'
                ),
                lp.DimRevealListFrame(
                    [
                        pl.TextSize(-1),
                        'We can learn a few things from the software engineers that are programming all day every day',
                        [pl.Underline('Version control'), 'or', pl.Underline('source control'), 'is a way of tracking',
                         'changes to code over time. You can get the full history of the project, and multiple',
                         'people can work on the same project at the same time and later merge the changes together.',
                         git_mono, 'is the gold standard for this.'],
                        ['Share', git_mono, 'repositories with the world via Github (or others), allowing anyone to '
                         'use and improve your project'],
                        "Automated testing of your code allows you to make changes ensuring it won't break anything",
                        "Input validation is useful for when others interact with your model directly",
                        'Use an integrated development environment (IDE) such as PyCharm or VS Code for better code '
                        'completion and linking',
                        'Automatically run tests, style your code, deploy Python packages or web apps, and more with '
                        'continuous integration/continuous deployment (CI/CD)'
                    ],
                    title='General Programming'
                ),
                lp.DimRevealListFrame(
                    [
                        ['Python can work with the files on your computer through the', open_mono, 'command and the',
                         os_mono, pathlib_mono,
                         'and', shutil_mono, 'modules'],
                        'Get unique items, unions, intersections using sets',
                        'Override how objects work by overriding double-underscore (dunder) class methods',
                        'Modify existing functions using decorators',
                        'Store Python objects by pickling them',
                        'Check yourself, make your code easier to understand, and power up your IDE using type annotations',
                        'Structure projects using packages and modules',
                        'Isolate project requirements using virtual environments',
                    ],
                    title='Python Programming'
                ),
                lp.DimRevealListFrame(
                    [
                        pl.TextSize(-1),
                        Hyperlink(
                            'https://product.hubspot.com/blog/git-and-github-tutorial-for-beginners',
                            'Get Started with Git and Github'
                        ),
                        Hyperlink(
                            'https://desktop.github.com/',
                            'Github Desktop is an App that Makes Git Easy'
                        ),
                        Hyperlink(
                            'https://realpython.com/python-testing/',
                            'Get Started with Automated Testing in Python'
                        ),
                        Hyperlink(
                            'https://www.youtube.com/watch?v=IL3eZYiV70g',
                            'Intro to Input Validation in Python'
                        ),
                        Hyperlink(
                            'https://www.jetbrains.com/pycharm/',
                            'PyCharm IDE'
                        ),
                        Hyperlink(
                            'https://code.visualstudio.com/',
                            'Visual Studio Code (VS Code) IDE'
                        ),
                        Hyperlink(
                            'https://semaphoreci.com/blog/cicd-pipeline',
                            'Intro to CI/CD'
                        ),
                        Hyperlink(
                            'https://github.com/features/actions',
                            'CI/CD Using Github Actions'
                        ),
                        Hyperlink(
                            'https://www.pythonforbeginners.com/files/reading-and-writing-files-in-python',
                            'Intro to Reading and Writing Files with Python'
                        ),
                        Hyperlink(
                            'https://realpython.com/python-pathlib/',
                            'Beyond the Basics of Working with Files in Python'
                        ),
                    ],
                    title='Programming Resources 1'
                ),
                lp.DimRevealListFrame(
                    [
                        pl.TextSize(-1),
                        Hyperlink(
                            'https://realpython.com/python-sets/',
                            'Work with Sets in Python'
                        ),
                        Hyperlink(
                            'https://dbader.org/blog/python-dunder-methods',
                            'Get Started with Dunder Methods in Python'
                        ),
                        Hyperlink(
                            'https://realpython.com/python-data-classes/',
                            'Advanced Dataclasses'
                        ),
                        Hyperlink(
                            'https://ipython.readthedocs.io/en/stable/config/integrating.html',
                            'Rich Object Display in Jupyter'
                        ),
                        Hyperlink(
                            'https://realpython.com/primer-on-python-decorators/',
                            'Get Started with Python Decorators'
                        ),
                        Hyperlink(
                            'https://www.datacamp.com/community/tutorials/pickle-python-tutorial',
                            'Store Python Objects with pickle and dill'
                        ),
                        Hyperlink(
                            'https://dev.to/dstarner/using-pythons-type-annotations-4cfe',
                            'Intro to Type Annotations in Python'
                        ),
                        Hyperlink(
                            'https://docs.python-guide.org/writing/structure/',
                            'Intro to Project Structure in Python'
                        ),
                        Hyperlink(
                            'https://www.dabapps.com/blog/introduction-to-pip-and-virtualenv-python/',
                            'Introduction to Virtual Environments in Python'
                        ),
                        Hyperlink(
                            'https://realpython.com/pipenv-guide/',
                            'Virtual Environments Made Easy with pipenv'
                        )
                    ],
                    title='Programming Resources 2'
                )

            ],
            title='Programming'
        ),
        pl.Section(
            [
                lp.DimRevealListFrame(
                    [
                        Hyperlink(
                            'https://docs.python-guide.org/',
                            "The Hitchhiker's Guide to Python"
                        ),
                        Hyperlink(
                            'https://realpython.com/',
                            'Real Python'
                        ),
                        Hyperlink(
                            'https://automatetheboringstuff.com/',
                            'Automate the Boring Stuff with Python'
                        ),
                        Hyperlink(
                            'https://pbpython.com/',
                            'Practical Business Python'
                        )

                    ],
                    title='General Resources'
                )
            ],
            title='Extras'
        ),
        pl.PresentationAppendix([lecture.pyexlatex_resources_frame]),
    ]
Ejemplo n.º 6
0
def get_content():
    pd_mono = pl.Monospace('pandas')
    dfs_mono = pl.Monospace('DataFrames')
    df_mono = pl.Monospace('DataFrame')
    next_slide = lp.Overlay([lp.UntilEnd(lp.NextWithIncrement())])
    df_to_excel_example = pl.Python(
        "df.to_excel('data.xlsx', sheet_name='My Data', index=False)")
    df_from_excel_example = pl.Python(
        "df = pd.read_excel('data.xlsx', sheet_name='My Data')")
    index_false_mono = pl.Monospace('index=False')
    addin_install_mono = pl.Monospace('xlwings addin install')
    addin_install_success = pl.Monospace(
        'Successfuly installed the xlwings add-in! Please restart Excel.')
    random_seed_py = pl.Monospace('random_seed.py')
    random_seed_excel = pl.Monospace('random_seed.xlsm')
    quickstart_mono = pl.Monospace('xlwings quickstart')
    quickstart_project_mono = pl.Monospace(
        'xlwings quickstart my_project_name')
    cd_mono = pl.Monospace('cd')
    xw_func_decorator = pl.Monospace('@xw.func')
    xw_arg_decorator = pl.Monospace('@xw.arg')
    xw_ret_decorator = pl.Monospace('@xw.ret')
    x_mono = pl.Monospace('x')
    expand_table_mono = pl.Monospace("expand='table'")
    random_choice_mono = pl.Monospace('random_choice')
    random_choice_py = pl.Monospace('random.choices')

    lecture = get_combining_excel_python_lecture()
    pd_read_write_exercise = get_read_write_excel_pandas_lab_lecture(
    ).to_pyexlatex()
    xlwings_exercise = get_read_write_xlwings_lab_lecture().to_pyexlatex()

    read_from_excel_example = pl.Python("""
my_value = sht.range("G11").value  # single value
# all values in cell range
my_value = sht.range("G11:F13").value  
# expands cell range down and right getting all values
my_values = sht.range("G11").expand().value  
""")

    write_to_excel_example = pl.Python("""
sht.range("G11").value = 10
sht.range("G11").value = [10, 11]  # horizontal
sht.range("G11:G12").value = [10, 11]  # vertical
# table, DataFrame from elsewhere
sht.range("G11").value = df  
""")

    return [
        pl.Section([
            lp.DimRevealListFrame([
                "We have learned how to use both Excel and Python to solve problems. Throughout this process, there "
                "were advantages and disadvantages of each tool for each problem.",
                "I wanted you to know both tools so you could pick whichever is best to tackle your problem",
                "For larger problems, you'll likely find some parts are better with Excel and some with Python",
                "After this lecture, you won't need to choose one anymore, you can use both at once."
            ],
                                  title='Leveraging the Power of Both Tools'),
        ],
                   title='Introduction'),
        pl.Section([
            lp.DimRevealListFrame([
                [pd_mono, 'has built-in tools for working with Excel'],
                [
                    pd_mono, 'can read Excel workbooks into', dfs_mono,
                    'and it can write', dfs_mono, 'back to Excel workbooks'
                ],
                'For simple uses, this may be enough. If you just need to get data from somewhere once and put it in your '
                'workbook, or you have your data in Excel and want to analyze it in Python, this is sufficient',
                [
                    "If you want to manipulate your workbook from Python, or you want to run Python code from your "
                    "workbook, look to", xlwings_mono
                ]
            ],
                                  title=f'How Far does {pd_mono} Get Us?'),
            lp.Frame([
                lp.Block([
                    df_from_excel_example,
                    pl.VSpace(-0.3),
                    pl.UnorderedList([
                        "If you don't pass a sheet name, it will take the first sheet."
                    ])
                ],
                         title='Reading Excel Files',
                         overlay=next_slide),
                pl.VFill(),
                lp.Block(
                    [
                        df_to_excel_example,
                        pl.VSpace(-0.3),
                        pl.UnorderedList(
                            [[
                                'We are passing', index_false_mono,
                                'because usually the 0, 1, 2 ... index is not useful'
                            ],
                             [
                                 "If you had set your index to something useful, then don't include",
                                 index_false_mono
                             ]])
                    ],
                    title='Writing to Excel Files',
                    overlay=next_slide),
                pl.VFill(),
                lp.AlertBlock([[
                    'When', pd_mono,
                    'writes to a workbook, it replaces the file. Do not write over an existing '
                    'workbook that you want to keep!'
                ]],
                              title='Careful When Writing!',
                              overlay=next_slide),
            ],
                     title=f'Reading and Writing to Excel Files with {pd_mono}'
                     ),
            lp.Frame([
                InClassExampleBlock([
                    pl.UnorderedList([
                        'Download the contents of the "Read Write Excel Pandas" folder in Examples',
                        'Ensure that you put the Excel file and notebook in the same folder for it to work',
                        'Follow along with the notebook'
                    ])
                ],
                                    title=
                                    f'Read and Write to Excel using {pd_mono}')
            ],
                     title='Showcasing Reading and Writing to Excel Files'),
            pd_read_write_exercise.presentation_frames(),
        ],
                   title=f'To and From Excel with {pd_mono}',
                   short_title=pd_mono),
        pl.Section([
            lp.TwoColumnGraphicDimRevealFrame([[
                'The easiest way to use Python from in Excel, or Excel from in Python, is',
                xlwings_mono
            ], "In Windows, it's based off the Microsoft COM API, which is some common tools they give for creating "
                                               "plugins.",
                                               "It's still in active development, but overall it works pretty well and is far beyond where we were "
                                               "a few years ago"],
                                              graphics=[
                                                  images_path(
                                                      'xlwings-logo.png')
                                              ],
                                              title=
                                              f'Introducing {xlwings_mono}'),
            lp.DimRevealListFrame(
                [['There are two main ways to use', xlwings_mono],
                 [
                     'You can',
                     pl.
                     Bold('manipulate Excel from Python,'),
                     'which gives you the full power of Excel from',
                     "within Python. In this class we'll focus on reading and writing values, but you can do anything",
                     "that you would normally be able to in Excel, but by executing Python code."
                 ],
                 [
                     'Or you can',
                     pl.Bold('run Python from Excel'),
                     'using one of two approaches:',
                     pl.Underline('Python as a VBA replacement'), 'and',
                     pl.Underline('user-defined functions (UDFs)')
                 ],
                 'We will focus on manipulating Excel from Python in this class. I encourage you to explore '
                 'the other two approaches on your own.'],
                title=f'What are the Main Ways to use {xlwings_mono}?'),
            lp.TwoColumnGraphicDimRevealFrame([
                pl.TextSize(-1),
                [
                    xlwings_mono,
                    'allows us to write Python values into Excel and fetch Excel values into Python'
                ],
                'There is also a complete VBA API, meaning you can do everything that you could do with VBA '
                'from within Python, which means you have the full capabilities of Excel within Python',
                'There are also convenient features to work with entire tables at once rather than '
                'a single value'
            ],
                                              graphics=[
                                                  images_path(
                                                      'python-excel-logo.png')
                                              ],
                                              title=
                                              'Using Python to Drive Excel Models'
                                              ),
            lp.Frame([
                lp.Block([read_from_excel_example],
                         title='Read Values from Excel'),
                lp.Block([write_to_excel_example],
                         title='Write Values to Excel')
            ],
                     title='Write and Read Values to and from Excel'),
            InClassExampleFrame([
                'Download the contents of the "xlwings" folder in Examples',
                'Ensure that you put the Excel file and notebook in the same folder for it to work',
                'Follow along with the notebook'
            ],
                                title=f'How to Use {xlwings_mono}',
                                block_title=f'Trying out {xlwings_mono}'),
            xlwings_exercise.presentation_frames(),
        ],
                   title=
                   f'Introducing Full Python-Excel Connection with {xlwings_mono}',
                   short_title=f'{xlwings_mono}'),
        pl.PresentationAppendix([
            lecture.pyexlatex_resources_frame,
            pd_read_write_exercise.appendix_frames(),
            xlwings_exercise.appendix_frames(),
        ])
    ]
Ejemplo n.º 7
0
 def __str__(self):
     base_str = super().__str__()
     return str(pl.TextColor(pl.Underline(base_str), 'blue'))
Ejemplo n.º 8
0
def get_content():
    random.seed(1000)
    ev_bet = (999999 / 1000000) * 1 + (1 / 1000000) * (-750001)
    xlwings_mono = pl.Monospace('xlwings')
    pd_mono = pl.Monospace('pandas')
    quickstart_mono = pl.Monospace('quickstart')

    read_from_excel_example = pl.Python("""
my_value = xw.Range("G11").value  # single value
# all values in cell range
my_value = xw.Range("G11:F13").value  
# expands cell range down and left getting all values
my_values = xw.Range("G11").expand().value  
    """)

    write_to_excel_example = pl.Python("""
xw.Range("G11").value = 10
xw.Range("G11").value = [10, 11]  # horizontal
xw.Range("G11").value = [[10], [11]]  # vertical
xw.Range("G11").value = [[10, 11], [12, 13]]  # table
    """)

    ball_options = ['fill', 'circle', 'inner sep=8pt']

    blue_ball_options = ball_options + ['blue']

    red_ball_options = ball_options + ['red']

    def rand_pos():
        return random.randrange(-150, 150) / 100

    blue_nodes = [
        lg.Node(None, (rand_pos(), rand_pos()), options=blue_ball_options)
        for _ in range(10)
    ]
    red_nodes = [
        lg.Node(None, (rand_pos(), rand_pos()), options=red_ball_options)
        for _ in range(10)
    ]

    red_blue_ball_graphic = lg.TikZPicture([
        lg.Rectangle(5, 5, shape_options=['blue', 'thick']), *blue_nodes,
        *red_nodes
    ])

    lecture = get_monte_carlo_lecture()
    intro_mc_python_lab = get_intro_monte_carlo_lab_lecture().to_pyexlatex()
    mc_python_lab = get_python_retirement_monte_carlo_lab_lecture(
    ).to_pyexlatex()
    mc_excel_lab = get_excel_retirement_monte_carlo_lab_lecture().to_pyexlatex(
    )

    return [
        pl.Section([
            lp.
            TwoColumnGraphicDimRevealFrame([
                [
                    pl.Bold('Monte Carlo Simulation'),
                    'is a technique which allows understanding the probability '
                    'of acheiving certain outputs from a model.'
                ],
                'This gives the modeler a greater understanding of the likelihood of different outputs, rather '
                'than relying on a single number',
            ],
                                           graphics=[
                                               images_path(
                                                   'random-numbers.jpg')
                                           ],
                                           title=
                                           'What is Monte Carlo Simulation?'),
            lp.DimRevealListFrame([
                r'Imagine you have a one-time opportunity to place a bet for \$1. ',
                r'If you win the bet, you will receive \$2. If you lose the bet, you will lose \$750,000. '
                r'You cannot avoid the payment by declaring bankruptcy.',
                r'The odds of winning the bet are 999,999/1,000,000. In 1/1,000,000 you lose the \$750,000.',
                fr'The expected profit from the bet is \${ev_bet:.2f}. Should you take it? Depends on your '
                fr'risk tolerance.',
                'Therefore not only the expected outcome matters, but also what other outcomes may occur and '
                'their probabilities.'
            ],
                                  title='Why Use Monte Carlo Simulation?'),
            lp.GraphicFrame(explore_parameters_graphic(),
                            title='Monte Carlo Simulation in One Picture'),
            lp.DimRevealListFrame([
                'Monte Carlo simulation is carried out similarly to external scenario analysis.',
                'The main difference is that we manually picked specific cases for the inputs with scenario '
                'analysis.',
                'In Monte Carlo simulation, we assign distributions to the inputs, and input values are drawn '
                'from the distributions for each run of the model',
                'Finally, we can fit a probability distribution to the outputs to be able to talk about the '
                'chance of a certain outcome occurring'
            ],
                                  title=
                                  'Basic Process for Monte Carlo Simulation')
        ],
                   title='Introduction'),
        pl.Section(
            [
                lp.DimRevealListFrame([
                    'Monte Carlo simulation can be applied to any model',
                    'It is generally easier to run them in Python than in Excel.',
                    "With pure Excel, you're either going to VBA or hacking something with data tables",
                    'In Python, just loop for N iterations, each time drawing inputs, running the model, and collecting '
                    'outputs.',
                    [
                        'We will start with a pure Python model, then move to using',
                        xlwings_mono, 'to add Monte Carlo '
                        'simulations to our Excel models.'
                    ],
                ],
                                      title=
                                      'Running Monte Carlo Simulations - Python or Excel?'
                                      ),
                lp.Frame([
                    lp.Block([
                        r'You have \$1,000 now and need to pay \$1,050 in one year. You have available to you '
                        r'two assets: a risk free asset that returns 3%, and a stock that returns 10% with a '
                        r'20% standard deviation. How much should you invest in the two assets to maximize '
                        r'your probability of having at least \$1,050 in one year?'
                    ],
                             title='An Investment Problem'),
                    pl.VFill(),
                    pl.UnorderedList([
                        lp.DimAndRevealListItems([
                            'We must first construct the basic model which gets the portfolio value for given '
                            'returns',
                            'Then draw values of the stock return from a normal distribution, and run the model '
                            'many times and visualize the outputs. ',
                            'Then repeat this process with each weight to determine the best weight.'
                        ])
                    ])
                ],
                         title='An Example Application'),
                InClassExampleFrame([
                    'Go to the course site and download the Jupyter notebook "MC Investment Returns.ipynb" from '
                    'Monte Carlo Examples',
                    'I will go through this example notebook to solve the problem from the prior slide.'
                ],
                                    title='Simluating Portfolio Values',
                                    block_title=
                                    'Example for Simulating Portfolio Values'),
                pl.TextSize(-2),
                intro_mc_python_lab.presentation_frames(),
                pl.TextSize(0),
            ],
            title='Running a First Monte Carlo Simulation',
            short_title='Run MC',
        ),
        pl.Section(
            [
                lp.Frame([
                    pl.TextSize(-2), 'For the model given by:',
                    pl.Equation(str_eq='y = f(X)', inline=False),
                    pl.Equation(str_eq='X = [x_1, x_2, ..., x_n]',
                                inline=False),
                    pl.UnorderedList([[
                        pl.Equation(str_eq='y:'), 'Model output'
                    ], [pl.Equation(str_eq='X:'), 'Model input matrix'],
                                      [
                                          pl.Equation(str_eq='x_i:'),
                                          'Value of $i$th $x$ variable'
                                      ]]),
                    'To run $N$ Monte Carlo simulations, follow the following steps:',
                    pl.OrderedList(
                        [[
                            'Assign a probability distribution for each',
                            pl.Equation(str_eq='x_i')
                        ],
                         [
                             'For each',
                             pl.Equation(str_eq='x_i'),
                             'randomly pick a value from its probability distribution. Store them as',
                             pl.Equation(str_eq='X_j')
                         ],
                         [
                             'Repeat the previous step $N$ times, yielding',
                             pl.Equation(str_eq='[X_1, X_2, ..., X_N]')
                         ],
                         [
                             'For each',
                             pl.Equation(str_eq='X_j'), 'calculate',
                             pl.Equation(str_eq='y_j = f(X_j)')
                         ],
                         [
                             'Store the values of',
                             pl.Equation(str_eq='X_j'), 'mapped to',
                             pl.Equation(str_eq='y_j')
                         ],
                         [
                             'Visualize and analyze',
                             pl.Equation(str_eq='y_j'), 'versus',
                             pl.Equation(str_eq='X_j')
                         ]])
                ],
                         title='Monte Carlo Simulation Process'),
                lp.DimRevealListFrame([
                    'There are a multitude of outputs we can get from a Monte Carlo simulation. We saw a few '
                    'already in the example.',
                    [
                        pl.Bold('Outcome probability distributions'),
                        'are the main output. We saw this with two '
                        'approaches in the example, a',
                        pl.Underline('histogram'), 'and a',
                        pl.Underline('probability table.')
                    ],
                    [
                        'We also examined the',
                        pl.Bold('probability of a certain outcome'),
                        'in whether we reached '
                        'the desired cash.'
                    ],
                    [
                        'The last main output is examining the',
                        pl.Bold('relationship between inputs and outputs.'),
                        'for which common approaches include',
                        pl.Underline('scatter plots'), 'and',
                        pl.Underline('regressions.')
                    ]
                ],
                                      title=
                                      'Outputs from Monte Carlo Simulation'),
                lp.TwoColumnGraphicDimRevealFrame(
                    [
                        pl.TextSize(-3),
                        'The outcome probability distribution represents the chance of receiving different '
                        'outcomes from your model.',
                        'There are two main ways to visualize a probability distribution: a plot and a table.',
                        [
                            'The plot, usually a',
                            pl.Underline('histogram'), 'or',
                            pl.Underline('KDE'),
                            'gives a high-level overview of the probabilities and can uncover any non-normal '
                            'features of the distribution.'
                        ],
                        [
                            'The probability table represents the chance of receiving the given value or '
                            'lower.'
                        ],
                        'The Value at Risk (VaR) is a common measure calculated in the industry, and it represents '
                        'the probability of losing at least a certain amount. This would be a subset of this analysis '
                        'and so this analysis can be used to calculate VaR',
                    ],
                    graphics=[
                        images_path('outcome-probability-distribution.png'),
                        lt.Tabular([
                            pl.MultiColumnLabel('Probability Table', span=2),
                            lt.TopRule(),
                            lt.ValuesTable.from_list_of_lists(
                                [['Probability', 'Value']]),
                            lt.TableLineSegment(0, 1),
                            lt.ValuesTable.from_list_of_lists(
                                [['25%', '1020'], ['50%', '1039'],
                                 ['75%', '1053']]),
                            lt.BottomRule()
                        ],
                                   align='c|c')
                    ],
                    title='Outcome Probability Distributions',
                    graphics_on_right=False,
                ),
                lp.TwoColumnGraphicDimRevealFrame(
                    [
                        'Imagine a box which contains red and blue balls. You do not know in advance how many there '
                        'are of each color.',
                        'You want to estimate the probability of getting a blue ball when pulling a ball from the box.',
                        'To evaluate this, you grab a ball, write down its color, and put it back, 1,000 times.',
                        'You pull a blue ball in 350 out of the 1,000 trials. What is the probability of getting blue?'
                    ],
                    graphics=[red_blue_ball_graphic
                              ],
                    title='Probability of a Certain Outcome - A Simple Example'
                ),
                lp.DimRevealListFrame([
                    'We followed the same logic when estimating the probability of receiving our desired cash '
                    'in the investment example.',
                    pl.Equation(
                        str_eq=
                        fr'p = \frac{{{pl.Text("Count of positive outcomes")}}}{{{pl.Text("Count of trials")}}}'
                    ),
                    [
                        'For the balls example, this is simply',
                        pl.Equation(str_eq=r'p = \frac{350}{1000} = 0.35'),
                    ],
                    [
                        'In the investment example, we used', pd_mono,
                        'to check for each trial, whether it was a '
                        'positive outcome (made it a 1) or not (made it a 0). Then the sum is the count of '
                        'positive outcomes and so the mean is the probability.'
                    ],
                ],
                                      title=
                                      'Probability of a Certain Outcome, Formally'
                                      ),
                lp.DimRevealListFrame([
                    'Monte Carlo simulation can also provide a more comprehensive look at the relationship between '
                    'inputs and outputs.',
                    'While sensitivity analysis can be used to estimate the relationship between an input and '
                    'output, it is usually done with other inputs at their base case',
                    'The values of inputs may affect how other inputs affect the output. E.g. for the retirement '
                    'model, an increase in interest rate increases wealth more if the initial salary was higher.',
                    'As all the inputs change each time, you can get a more realistic view of the relationship, e.g. '
                    'some trials with a higher interest rate will have high salary and some will have low salary.'
                ],
                                      title=
                                      'Why Monte Carlo Simulations Help Understand Inputs vs. Outputs'
                                      ),
                lp.TwoColumnGraphicDimRevealFrame(
                    [
                        pl.TextSize(-1),
                        'A scatter plot is a simple way to visualize the relationship between two variables',
                        'If there is a relationship, you will see some defined pattern in the points. This may be '
                        'somewhat of an upward or downward line (linear relationship) or some other shape such '
                        'as a U (non-linear relationship).',
                        'If there is no relationship, then there will just be a random cloud of points (lower '
                        'plot) or a horizontal line.'
                    ],
                    graphics=[
                        images_path('scatter-plot-line.png'),
                        images_path('scatter-plot-no-relationship.png')
                    ],
                    graphics_on_right=False,
                    title=
                    'Visualizing the Relationship between Inputs and Outputs'),
                lp.TwoColumnGraphicDimRevealFrame([
                    pl.TextSize(-2),
                    'The scatter plots help give a broad understanding of the relationship but do not answer the '
                    'question, how much will my output change if my input changes? E.g. if I earn 10,000 more '
                    'for a starting salary, how much sooner can I retire?',
                    'Simply increasing the input in your model and checking the output is not enough, because it '
                    'does not take into account how all the other variables may be changing.',
                    'Multivariate regression is a general tool which is good at answering these kinds of questions, '
                    'while taking into account all the changing inputs.'
                ],
                                                  graphics=[
                                                      images_path(
                                                          'excel-multivariate-reg.png'
                                                      )
                                                  ],
                                                  title=
                                                  'Numerically Analyzing the Relationships'
                                                  ),
                lp.DimRevealListFrame([
                    pl.TextSize(-1),
                    'The coefficient in a multivariate regression represents how much the outcome variable '
                    'changes with a one unit change in the input variable.',
                    'E.g. a coefficient of -.0002 on starting salary in explaining years to retirement would mean '
                    r'that a \$1 increase in starting salary is associated with a decrease in years to retirement by .0002 years, or '
                    r'a \$10,000 increase in starting salary is associated with a decrease in years to retirement by 2 years.',
                    'All interpretations are "all else constant", meaning that it does not consider relationships '
                    'between the inputs. E.g. if starting salary is higher because of a good economy, and interest '
                    'rates are also higher due to the good economy, the starting salary coefficient is not taking '
                    'into account the increase in interest rates.',
                    'Be careful about units. If you use decimals for percentages, you will need to multiply or '
                    'divide by 100 to get the effect in percentages.'
                ],
                                      title='How to use Multivariate Regression'
                                      ),
                InClassExampleFrame(
                    [
                        'I will now go through adding a Monte Carlo simulation to the Dynamic Salary Retirement '
                        'Model in Python',
                        'The completed example is on the course site in '
                        'Monte Carlo Examples',
                    ],
                    title='Adding Monte Carlo Simulation to a Formal Model',
                    block_title='Dynamic Salary Retirement with Monte Carlo'),
                mc_python_lab.presentation_frames(),
            ],
            title='A More Formal Treatment of Monte Carlo Simulation',
            short_title='Formal MC',
        ),
        pl.Section([
            lp.DimRevealListFrame([
                'In pure Excel, it is much more difficult to run a Monte Carlo Simulation',
                'Without going to VBA, typically the only way is to use a data table',
                'A data table can be used in situations where you only want to have one or two inputs '
                'varying at once. Just generate the random inputs and use them as the axes of the data table',
                'If you want to vary more than two inputs, VBA or Python would be required',
                'There are also add-ons that accomplish this but they are usually not free'
            ],
                                  title=
                                  "How is it Different Running MC in Excel?"),
            lp.DimRevealListFrame([
                'The process for Monte Carlo Simulation which works for any number of variables is '
                'very similar to what we were doing in Python.',
                'We are still just changing the inputs, running the model, and storing the outputs from each run',
                [
                    'Using', xlwings_mono,
                    'from Python code we can change and retrieve the values of cells'
                ],
                'This allows us to change inputs, run the model, and store outputs, just as in Python, but running our Excel model.',
                'We can either analyze the outputs in Python or output them back to Excel for analysis'
            ],
                                  title=
                                  'Monte Carlo in Excel with More than Two Variables'
                                  ),
            InClassExampleFrame([
                'Go to the course site and download the "Dynamic Salary Retirement Model.xlsx" and '
                '"Excel Monte Carlo.ipynb" from the Monte Carlo Examples',
                'Open up the Jupyter notebook and follow along with me',
                'The completed Excel model is also there in case you lose track. Visualizations '
                'were added after running the Jupyter notebook on the original Excel model.',
            ],
                                title='Monte Carlo Excel Retirement Model',
                                block_title=
                                f'Using {xlwings_mono} to Run Monte Carlo Simulations'
                                ),
            mc_excel_lab.presentation_frames(),
        ],
                   title='Monte Carlo Simulation in Excel',
                   short_title='Excel MC'),
        pl.PresentationAppendix([
            lecture.pyexlatex_resources_frame,
            intro_mc_python_lab.appendix_frames(),
            mc_python_lab.appendix_frames(),
            mc_excel_lab.appendix_frames(),
        ])
    ]
def get_content():
    random.seed(1000)
    dcf_overview_graphic = get_dcf_graphic()
    cc_graphic = get_dcf_graphic(include_output=False, include_fcf=False)
    fcf_graphic = get_dcf_graphic(include_output=False, include_coc=False)

    lecture = get_dcf_cost_capital_lecture()
    enterprise_equity_value_excercise = get_enterprise_value_lab_lecture().to_pyexlatex()
    cost_equity_exercise = get_dcf_cost_equity_lab_lecture().to_pyexlatex()
    cost_debt_exercise = get_dcf_cost_debt_lab_lecture().to_pyexlatex()
    wacc_graphics = get_wacc_graphics()

    return [
        pl.Section(
            [
                lp.DimRevealListFrame(
                    [
                        pl.JinjaTemplate('A {{ "discounted cash flow valuation (DCF)" | Bold }} is a method of '
                                         'determining the value of a stock.').render(),
                        'Other ways include the dividend discount model and approaches based on comparables',
                        'The dividend discount model only works well for stable companies that pay dividends with '
                        'constant growth.',
                        'Comparable approaches can give a rough idea of a valuation but never take into account the '
                        'specifics of the company',
                        'DCF valuation can be applied to any company and is based on the particulars of the company'
                    ],
                    title='What is a DCF?'
                ),
                lp.GraphicFrame(
                    dcf_overview_graphic,
                    title='The DCF in One Picture'
                ),
                lp.Frame(
                    [
                        lp.Block(
                            [
                                pl.Equation(str_eq=r'V = \sum_{t=0}^T \frac{CF^t}{(1 + r)^t}', inline=False)
                            ],
                            title='Financial Asset Value'
                        ),
                        pl.UnorderedList([lp.DimAndRevealListItems([
                            'The value of any financial asset is the present value of its future cash flows',
                            'The cash flows for a stock are dividends. The dividend discount model takes the present '
                            'value of future dividends.',
                            'To find the value of a business, find the present value of its future free cash flows'
                        ], vertical_fill=True)]),
                    ],
                    title='Motivating the DCF'
                ),
                lp.TwoColumnGraphicDimRevealFrame(
                    [
                        pl.TextSize(-1),
                        ['The goal of cost of capital estimation is to determine the',
                         pl.Bold('weighted average cost of capital (WACC)')],
                        ['This can broadly be broken down into two components: estimating the',
                         pl.Underline('cost of equity'), 'and estimating the', pl.Underline('cost of debt')],
                        'Cost of equity is typically estimated using the Capital Asset Pricing Model (CAPM)',
                        'Cost of debt is usually estimated from the interest payments and book value of debt'
                    ],
                    graphics=[lp.adjust_to_full_size_and_center(cc_graphic)],
                    title='Overview of Cost of Capital Estimation'
                ),
                lp.TwoColumnGraphicDimRevealFrame(
                    [
                        pl.TextSize(-1),
                        'The goal of free cash flow estimation is to determine the historical and future '
                        'free cash flows (FCF) for the company.',
                        'Historical financial statements, including the income statement, balance sheet, and '
                        'statement of cash flows are used to determine historical FCF',
                        'It is the job of the analyst building the model to project those FCF into the future',
                        'This is usually done by projecting the financial statements into the future'
                    ],
                    graphics=[lp.adjust_to_full_size_and_center(fcf_graphic)],
                    title='Overview of Free Cash Flow Estimation'
                )
            ],
            title='Introduction to Discounted Cash Flow (DCF) Valuation',
            short_title='DCF Intro'
        ),
        pl.Section(
            [
                lp.DimRevealListFrame(
                    [
                        'The enterprise value of the business is the asset value or the cost to purchase the '
                        'entire company',
                        pl.Equation(
                            str_eq=f'{pl.Text("Enterprise Value")} = {pl.Text("Equity Value")} + '
                                   f'{pl.Text("Debt Value")} - {pl.Text("Cash")}'
                        ),
                        'A stock represents only the equity value or market capitalization of a business',
                        'By determining the enterprise value, we can back into the equity value to get the stock price'
                    ],
                    title='Enterprise Value vs. Equity Value'
                ),
                pl.TextSize(-1),
                enterprise_equity_value_excercise.presentation_frames(),
                pl.TextSize(0),
            ],
            title='Enterprise and Equity Value',
            short_title='EV'
        ),
        pl.Section(
            [
                lp.Frame(
                    [
                        pl.TextSize(-1),
                        lp.Block(
                            [
                                EquationWithVariableDefinitions(
                                    r'r_i = r_f + \beta (r_m - r_f) + \epsilon',
                                    [
                                        '$r_i$: Return on stock $i$',
                                        '$r_f$: Return on risk free asset',
                                        '$r_m$: Return on market portfolio',
                                        r'$\beta$: Covariance of stock returns with market risk premium',
                                        r'$\epsilon$: Idiosyncratic return, mean 0',
                                    ]
                                )
                            ],
                            title='Capital Asset Pricing Model (CAPM)'
                        ),
                        pl.UnorderedList([lp.DimAndRevealListItems([
                            'We will use historical stock price data along with CAPM to produce an estimate of the '
                            'cost of equity.',
                            'Ultimately, $r_i$ is the estimate of the cost of equity',
                        ], vertical_fill=True)])

                    ],
                    title='How Can CAPM be used for Estimating the Cost of Equity?'
                ),
                lp.Frame(
                    [
                        lp.Block(
                            [
                                pl.Equation(str_eq=r'r_i = r_f + \beta (r_m - r_f) + \epsilon')
                            ],
                            title='Capital Asset Pricing Model (CAPM)'
                        ),
                        pl.UnorderedList([lp.DimAndRevealListItems([
                            r'The three returns can all be estimated from historical data. Therefore $\beta$ and '
                            r'$\epsilon$ are the unknowns. But $\epsilon$ has mean zero so we can ignore it '
                            r'for estimation.',
                            'We will estimate the historical beta, then assume that the beta is still valid today to '
                            'come up with the current $r_i$ as the cost of equity.',
                            r'$\beta$ can be estimated by regressing the historical stock returns of the company on '
                            r'the historical market risk premiums. The $\beta$ is then the coefficient of the market '
                            r'risk premium in the regression.'
                        ], vertical_fill=True)])
                    ],
                    title='Overview of Cost of Equity Estimation'
                ),
                InClassExampleFrame(
                    [
                        'Go to the course site and download "Determining the Cost of Equity.ipynb" '
                        'and "price data.xlsx" from '
                        'Cost of Equity Python Examples',
                        'Make sure that you place these two in the same folder',
                        'We are using historical prices to calculate the cost of equity using CAPM',
                        'We will use a risk free rate of 3% for the exercise',
                    ],
                    title='Using Price Data to Estimate Cost of Equity in Python',
                    block_title='Python CAPM Estimation'
                ),
                InClassExampleFrame(
                    [
                        'Go to the course site and download "DCF Cost of Equity.xlsx" from '
                        'Cost of Equity Excel Examples',
                        'We are using historical prices to calculate the cost of equity using CAPM',
                        'We will use a risk free rate of 3% for the exercise',
                    ],
                    title='Using Price Data to Estimate Cost of Equity in Excel',
                    block_title='Excel CAPM Estimation'
                ),
                cost_equity_exercise.presentation_frames(),
                lp.DimRevealListFrame(
                    [
                        'As we will cover in more detail when we get to WACC, we need to have the market values of '
                        'both equity and debt along with the costs to be able to caluclate the WACC.',
                        'The market value of equity for a publicly traded company is straightforward. Just calculate '
                        f'the {pl.Bold("market capitalization")} as the number of shares outstanding multiplied by the current '
                        'share price.',
                        'The market capitalization can be used directly as the market value of equity.'
                    ],
                    title='Market Value of Equity'
                )
            ],
            title='Cost of Equity Estimation',
            short_title='Equity'
        ),
        pl.Section(
            [
                lp.DimRevealListFrame(
                    [
                        'We want to estimate the cost of debt for the company, which more specifically should be '
                        'the marginal interest cost of raising one additional dollar via debt.',
                        ['There are two general approaches to estimating this: the',
                         pl.Underline('financial statements approach'), 'and the',
                         pl.Underline('market rate of bonds approach')],
                        'The market rate of bonds approach is better able to capture the current rate when it has '
                        'changed substantially over time, but it requires price, coupon, and maturity information on '
                        'a bond.',
                        'The financial statements approach uses only the income statement and balance sheet, and '
                        'represents a weighted average historical cost of debt.'

                    ],
                    title='Overview of Estimating the Cost of Debt'
                ),
                lp.DimRevealListFrame(
                    [
                        'The financial statements approach uses interest expense from the income statement and '
                        'total debt from the balance sheet to estimate the cost of debt',
                        'With this approach, we can estimate the cost of debt by a very simple formula',
                        pl.Equation(
                            str_eq=rf'r_d = \frac{{{pl.Text("Interest Expense")}}}{{{pl.Text("Total Debt")}}}'
                        ),
                        'Calculate this for the most recent data available and use this as the cost of debt'
                    ],
                    title='The Financial Statements Approach to Cost of Debt'
                ),
                lp.DimRevealListFrame(
                    [
                        'The cost of debt is about raising new debt, so it is more accurate to look at the market to '
                        'determine how much the company would have to pay for new debt.',
                        "The yield to maturity (YTM) of the company's bonds can be calculated. A weighted average of "
                        "the YTMs can be used as an estimate of the cost of debt.",
                        'The YTM is representing the required rate of return on the bond for the investor, which is '
                        'equivalent to the cost of the bond for the company',
                        'The YTM is simply the IRR of the bond, considering the current market price of the bond'
                    ],
                    title='The Market Rate of Bonds Approach to Cost of Debt'
                ),
                lp.DimRevealListFrame(
                    [
                        pl.TextSize(-1),
                        ['Debt has an interesting feature in our tax system: debt is', pl.Underline('tax deductible.')],
                        'The amount a company has to pay in income tax is taken as a percentage of earnings before tax (EBT).',
                        'As interest is taken out while calculating EBT, it lowers the tax payment.',
                        'Think about two hypothetical companies with the exact same operations, revenues, costs, etc. '
                        'One is financed completely with equity and the other with 50% debt. They will both have the '
                        'same EBIT but the EBT will be lower for the debt firm and so the taxes will be lower for the '
                        'debt firm, likely giving the debt firm a higher value than the equity firm.',
                        'What this means for cost of capital estimation is that all our calculations will be based on '
                        f'pre-tax numbers, then we multiply by $(1 - {pl.Text("tax rate")})$ to get the after-tax cost '
                        f'of debt to use in the WACC.'
                    ],
                    title='After-Tax Cost of Debt'
                ),
                cost_debt_exercise.presentation_frames(),
                lp.DimRevealListFrame(
                    [
                        "If you have taken a debt course, you should be familiar with the fact that bonds' values "
                        "change over time.",
                        'The value of a bond can be determined (just like any financial asset) by taking the present value of '
                        'future cash flows (here, interest and principal payments). ',
                        "If the discount rate for the company changes, the value of the bonds change, as the interest "
                        "payments are contracted and will remain the same",
                        "The discount rate will change when the riskiness of the firm's debt changes, e.g. taking on "
                        "additional debt, starting a new project, having a bad operating year, etc."
                    ],
                    title='What is the Market Value of Debt?'
                ),
                lp.DimRevealListFrame(
                    [
                        'Say a company issues a 3-year bond with a 10% coupon. When issued, the riskiness of the firm implies '
                        'it should have a 10% discount rate. In other words, the true cost of debt is 10%. '
                        'The bond is at par (value 1,000).',
                        'One year later, the firm has a bad year, and now lenders are requiring a 15% rate to lend to the company',
                        r'Due to this, the price of the existing bond has dropped to \$918.71.',
                        r'If we calculate the IRR on this \$918.71 bond, it comes to 15%, which is the true YTM or cost of debt',
                        'The coupon rate on the bond is still 10%, and the book value of debt on the balance sheet is '
                        'still 1,000 so based on the financial statements approach the cost of debt would still be 10%.'
                    ],
                    title='Why Should we Care about the Market Value of Debt?'
                ),
                lp.DimRevealListFrame(
                    [
                        'There are three main approaches to calculating the market value of debt for use in the '
                        'WACC calculation, depending on what data you have available',
                        ['If all you have is financial statements, you must just',
                         pl.Underline('assume the book value of debt equals the market value of debt.')],
                        ['If you also have an estimate of the current cost of debt obtained from the market as well '
                         'as an average maturity of debt, you can use the', pl.Underline('hypothetical bond approach.')],
                        ['Finally, if you have all the individual debt instruments, you can',
                         pl.Underline('calculate the market value of individual instruments.')]
                    ],
                    title='Approaches to Calculating the Market Value of Debt'
                ),
                lp.DimRevealListFrame(
                    [
                        "For the purposes of this class, we won't deal with seniority. But you should keep it in mind "
                        "in the future when estimating the market value and cost of debt.",
                        'Seniority represents the payoff order during bankruptcy. The most senior loans will be paid '
                        'first, and if there is still money left over, then the more junior loans will be paid.',
                        'As there is a higher expected value in recovery, senior loans are less risky and so should '
                        'have a lower rate associated with them.',
                        'In the prior exercise, when valuing individual debt instruments, we assumed a single cost of '
                        'debt, when in reality, it should be adjusted for the seniority.',
                    ],
                    title='Dealing with Seniority of Debt'
                ),
                InClassExampleFrame(
                    [
                        'Go to the course site and download "Market Value of Debt.ipynb" and "debt data.xlsx" from '
                        'Cost of Debt Examples',
                        'Ensure you have the Jupyter notebook and the Excel spreadsheet in the same folder.',
                        'We will go through the Jupyter notebook to show the three approaches to estimating '
                        'the market value of debt.'
                    ],
                    title='Calculating the Market Value of Debt',
                    block_title='MV Debt Example'
                ),
            ],
            title='Cost of Debt Estimation',
            short_title='Debt'
        ),
        pl.Section(
            [
                lp.Frame(
                    [
                        lp.Block(
                            [
                                EquationWithVariableDefinitions(
                                    f'{pl.Text("WACC")} = r_e w_e + r_d (1 - t) w_d',
                                    [
                                        '$r_e$: Cost of equity',
                                        '$w_e$: Weight of equity',
                                        '$r_d$: Pre-tax cost of debt',
                                        '$t$: Tax rate',
                                        '$w_d$: Weight of debt'
                                    ],
                                    space_adjustment=-0.4
                                )
                            ],
                            title='Weighted Average Cost of Capital (WACC)'
                        ),
                        pl.UnorderedList([lp.DimAndRevealListItems([
                            'So now from the prior sections we have the cost of equity, market value of equity, '
                            'cost of debt, and market value of debt.',
                            'The weights of debt and equity are found by dividing that market value by the sum of '
                            'both market values.'
                        ], vertical_fill=True)])
                    ],
                    title='Calculating WACC'
                ),
                lp.Frame(
                    [
                        pl.Center(adjust_to_size(wacc_graphics[0], 0.9, 0.35, keep_aspect_ratio=True)),
                        pl.Center(adjust_to_size(wacc_graphics[1], 0.9, 0.35, keep_aspect_ratio=True)),
                    ],
                    title='What the Weighted Part of WACC Means'
                )
            ],
            title='Putting it All Together: Calculating the WACC',
            short_title='WACC'
        ),
        pl.PresentationAppendix(
            [
                pl.TextSize(-2),
                lecture.pyexlatex_resources_frame,
                pl.TextSize(-1),
                enterprise_equity_value_excercise.appendix_frames(),
                cost_equity_exercise.appendix_frames(),
                cost_debt_exercise.appendix_frames(),
                pl.TextSize(0),
            ]
        )
    ]