示例#1
0
def multi_project_latex(data: List[dict]):
    contents = []
    for data_dict in data:
        contents.extend([
            project_latex(data_dict),
            pl.HLine(),
            pl.VSpace(0.5),
        ])

    del contents[-2:]  # remove last horizontal line and vertical spacing
    return contents
示例#2
0
    def _description_content(self) -> List:
        if self.description is None:
            return []

        return [
            '',  # separate paragraph
            Justifying(),  # return to justifying on both sides
            self.description,
            pl.VSpace(
                0.2)  # extra spacing looks good when description is included
        ]
示例#3
0
    def __init__(self,
                 contents,
                 title: str,
                 end_adjustment: float = -0.2,
                 num_cols: int = 1):
        self.end_adjustment = end_adjustment
        self.num_cols = num_cols

        if not isinstance(contents, (list, tuple)):
            contents = [contents]

        all_contents: Union[List[Union[pl.VSpace, str]],
                            MultiColumn] = [pl.VSpace(0.2)]
        for content in contents:
            all_contents.append(content)
            all_contents.append('')
        all_contents[-1] = pl.VSpace(end_adjustment)  # replace final spacing

        if self.num_cols > 1:
            all_contents = MultiColumn(all_contents, num_cols=self.num_cols)

        self.contents = pl.Section(all_contents, title=title)
        super().__init__()
示例#4
0
 def _get_contents(self):
     possible_items = [
         HangIndent(1),
         self._title_str,
         pl.Italics(self.journal_info)
         if self.journal_info is not None else None,
         self._with_coauthors,
         self.extra_info,
         *self._description_content,
         pl.VSpace(self.SPACE_BETWEEN_ADJUSTMENT),
     ]
     items = [item for item in possible_items if item is not None]
     if self.prevent_page_break:
         items = pl.NoPageBreak(items)
     return items
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),
    ]
示例#6
0
 def _get_contents(self):
     return [
         pl.Equation(str_eq=self.equation_str, inline=False),
         pl.VSpace(self.space_adjustment),
         pl.UnorderedList(self.definitions)
     ]
示例#7
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(),
        ])
    ]