Example #1
0
def test_single_figure_from_graphic():
    graphic = pl.Graphic(str(EXAMPLE_IMAGE_PATH))
    fig = pl.Figure([graphic])
    assert str(
        fig
    ) == '\\begin{figure}\n\\includegraphics[width=1.0\\textwidth]{Sources/nd-logo.png}\n\\end{figure}'
    fig = pl.Figure([graphic], position_str='[h!]')
    assert str(
        fig
    ) == '\\begin{figure}\n[h!]\n\\includegraphics[width=1.0\\textwidth]{Sources/nd-logo.png}\n\\end{figure}'
    fig = pl.Figure([graphic], caption='image')
    assert str(
        fig
    ) == '\\begin{figure}\n\\includegraphics[width=1.0\\textwidth]{Sources/nd-logo.png}\n\\caption{image}\n\\end{figure}'
    fig = pl.Figure.from_dict_of_names_and_filepaths(
        {'image': str(EXAMPLE_IMAGE_PATH)})
    assert str(
        fig
    ) == '\\begin{figure}\n\\includegraphics[width=0.45\\linewidth]{Sources/nd-logo.png}\n\\caption{image}\n\\end{figure}'
    fig = pl.Figure([graphic], caption='woo', short_caption='yeah')
    assert str(
        fig
    ) == '\\begin{figure}\n\\includegraphics[width=1.0\\textwidth]{Sources/nd-logo.png}\n\\caption[yeah]{woo}\n\\end{figure}'
    fig = pl.Figure([graphic],
                    caption='woo',
                    label='yeah',
                    centering=False,
                    landscape=True,
                    position_str=r'[h!]')
    assert str(
        fig
    ) == '\\begin{lfigure}\n[h!]\n\\includegraphics[width=1.0\\textwidth]{Sources/nd-logo.png}\n\\caption{woo}\n\\label{yeah}\n\\end{lfigure}'
    name = 'figure from single graphic document'
    fig.to_pdf_and_move(outfolder=GENERATED_FILES_DIR, outname=name)
    compare_pdfs_in_generated_vs_input_by_name(name)
Example #2
0
def test_graphics_from_multiple_subfigure_figure():
    graphic = pl.Graphic(str(EXAMPLE_IMAGE_PATH))
    subf1 = pl.Subfigure(str(EXAMPLE_IMAGE_PATH))
    subf2 = pl.Subfigure(str(EXAMPLE_IMAGE_PATH))
    fig = pl.Figure([subf1, subf2])
    graphics = fig.to_graphic_list()
    assert len(graphics) == 2
    for g in graphics:
        assert str(graphic) == str(g)
def test_figure_in_presentation():
    graphic = pl.Graphic(str(EXAMPLE_IMAGE_PATH), width=0.4)
    fig = pl.Figure([graphic], caption='My Figure')
    doc = pl.Presentation([
        pl.Section([
            pl.Frame([fig], title='Figure'),
        ], title="Section"),
    ], )
    name = 'presentation with figure'
    assert_same_or_generate_presentation(doc, name)
    doc.to_pdf(outfolder=GENERATED_FILES_DIR, outname=name)
    compare_pdfs_in_generated_vs_input_by_name(name)
def get_content():
    random.seed(1000)

    lecture = get_sensitivity_analysis_lecture()
    sensitivity_excel_lab = get_sensitivity_analysis_excel_lab_lecture().to_pyexlatex()
    dictionaries_lab = get_dictionaries_lab_lecture().to_pyexlatex()
    list_comp_lab = get_list_comprehensions_lab_lecture().to_pyexlatex()
    sensitivity_python_lab = get_sensitivity_analysis_python_lab_lecture().to_pyexlatex()
    appendix_frames = [
        lecture.pyexlatex_resources_frame,
        sensitivity_excel_lab.appendix_frames(),
        dictionaries_lab.appendix_frames(),
        list_comp_lab.appendix_frames(),
        sensitivity_python_lab.appendix_frames(),
    ]

    pd_mono = pl.Monospace('pandas')
    series_mono = pl.Monospace('Series')
    df_mono = pl.Monospace('DataFrame')
    apply_mono = pl.Monospace('apply')
    import_mono = pl.Monospace('import')
    for_mono = pl.Monospace('for')
    dict_mono = pl.Monospace('dict')
    np_mono = pl.Monospace('numpy')
    pd_mono = pl.Monospace('pandas')
    import_something_mono = pl.Monospace('import something')
    something_file = pl.Monospace('something.py')
    numpy_file = pl.Monospace('numpy.py')
    def_mono = pl.Monospace('def')
    class_mono = pl.Monospace('class')
    sensitivity_file_mono = pl.Monospace('sensitivity.py')
    sensitivity_import = pl.Monospace('import sensitivity')
    sensitivity_func_mono = pl.Monospace('sensitivity.sensitivity_hex_plots?')
    pip_install_mypackage = pl.Monospace('pip install mypackage')
    jupyter_install_mypackage = pl.Monospace('!pip install mypackage')
    itertools_product = pl.Monospace('itertools.product')
    sensitivity = pl.Monospace('sensitivity')

    series_ex_1 = pl.Python(
"""
>>> df = pd.DataFrame()
>>> df['Numbers'] = [1, 2, 3]
>>> df['Categories'] = ['apple', 'apple', 'orange']
>>> df
"""
    )
    series_ex_2 = pl.Python(
"""
>>> df['Categories']
0     apple
1     apple
2    orange
Name: Categories, dtype: object
>>> type(df['Categories'])
pandas.core.series.Series
"""
    )
    series_ex_3 = pl.Python(
"""
>>> cats = df['Categories']
>>> cats
0     apple
1     apple
2    orange
Name: Categories, dtype: object
>>> cats[2]
'orange'
>>> cats.index = ['a', 'b', 'c']
>>> cats
a     apple
b     apple
c    orange
Name: Categories, dtype: object
>>> cats['b']
'apple'
"""
    )

    list_comprehension_ex_1 = pl.Python(
"""
>>> out_values = []
>>> for i in range(5):
>>>     out_values.append(i + 10)
>>> out_values
[10, 11, 12, 13, 14]
"""
    )

    list_comprehension_ex_2 = pl.Python(
"""
>>> out_values = [i + 10 for i in range(5)]
>>> out_values
[10, 11, 12, 13, 14]
"""
    )
    dict_example = pl.Python(
"""
>>> coffee_levels_emotions = {
>>>     'high': 'happy',
>>>     'pretty high': 'happy',
>>>     'medium': 'neutral',
>>>     'low': 'sad',
>>>     'empty': 'desparate'
>>> }
>>> coffee_levels_emotions['pretty high']
'happy'
>>> for coffee_level, emotion in coffee_levels_emotions.items():
>>>     print(f"I'm {emotion} when my coffee is {coffee_level}")
"""
    )

    dict_printout = """
I'm happy when my coffee is high
I'm happy when my coffee is pretty high
I'm neutral when my coffee is medium
I'm sad when my coffee is low
I'm desparate when my coffee is empty
    """

    dict_printouts_mono = [pl.Monospace(item) for item in dict_printout.split('\n') if item]
    dict_printout_output = []
    for po in dict_printouts_mono:
        dict_printout_output.append(po)
        dict_printout_output.append('')

    dict_example_2 = pl.Python(
"""
>>> coffee_levels_emotions.update({'overflowing': 'burned'})
>>> coffee_levels_emotions['negative'] = 'confused'
>>> high_value = coffee_levels_emotions.pop('high')
>>> coffee_levels_emotions
{'pretty high': 'happy',
 'medium': 'neutral',
 'low': 'sad',
 'empty': 'desparate',
 'overflowing': 'burned',
 'negative': 'confused'}
>>> high_value
'happy'
"""
    )

    plain_sensitivity_example = pl.Python(
"""
inp1_values = [1, 2]
inp2_values = [4, 5]
results = []
for inp1 in inp1_values:
    for inp2 in inp2_values:
        result = model(inp1, inp2,)
        results.append(
            (inp1, inp2, result)
        )
pd.DataFrame(results, columns=['inp1', 'inp2',  'Result'])
"""
    )

    easy_sensitivity_example = pl.Python(
"""
from sensitivity import SensitivityAnalyzer

sensitivity_values = {
    'inp1': [1, 2],
    'inp2': [4, 5],
}
sa = SensitivityAnalyzer(sensitivity_values, model)
sa.df
"""
    )

    return [
        pl.Section(
            [
                lp.DimRevealListFrame(
                    [
                        'So far, I have given you some inputs to use and you have been getting one or more outputs from '
                        'those inputs',
                        'We have not considered how those inputs may change, and how that affects the outputs',
                        'This is where building a model vs. doing a calculation really starts to pay off'
                    ],
                    title='Moving from a Static Model'
                ),
                lp.GraphicFrame(
                    explore_parameters_graphic(),
                    title='How to Explore Inputs and their Affect on Outputs'
                ),
                lp.DimRevealListFrame(
                    [
                        pl.TextSize(-1),
                        'In this lecture, we will be discussing sensitivity analysis as an approach to exploring the '
                        'parameter space.',
                        'After we cover probabilistic modeling, we will revisit exploring the parameter space with other '
                        'methods: scenario analysis and Monte Carlo Simulation.',
                        'In sensitivity analysis, a fixed set of values for the parameters are chosen, while in Monte Carlo '
                        'Simulation, each parameter is assigned a distribution.',
                        'In scenario analysis, several realistic cases of the inputs are chosen which represent '
                        'possible real-world situations',
                        'All three methods may be used together to fully understand a model.'
                    ],
                    title='Methods of Parameter Exploration'
                ),
            ],
            title='Introduction to Parameter Exploration',
            short_title='Explore Parameters'
        ),
        pl.Section(
            [
                lp.Frame(
                    [
                        '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']

                        ]),
                        'Follow the following steps:',
                        pl.OrderedList([
                            ['Choose a set of values for each', pl.Equation(str_eq='x_i')],
                            ['Take the cartesian product of these values as',
                             pl.Equation(str_eq='[X_1, X_2, ..., X_m]')],
                            ['For each', pl.Equation(str_eq='X_i'), 'calculate', pl.Equation(str_eq='y_i = f(X_i)')],
                            ['Store the values of', pl.Equation(str_eq='X_i'), 'mapped to', pl.Equation(str_eq='y_i')],
                            ['Visualize', pl.Equation(str_eq='y_i'), 'versus', pl.Equation(str_eq='X_i')]
                        ])
                    ],
                    title='Sensitivity Analysis, Formally'
                ),
                get_sensitivity_analysis_example_frames(),
            ],
            title='Sensitivity Analysis Theory',
            short_title='SA Theory'
        ),
        pl.Section(
            [
                lp.GraphicFrame(
                    images_path('excel-data-table.png'),
                    title='Sensitivity Analysis in Excel'
                ),
                lp.DimRevealListFrame(
                    [
                        'There are two main ways to visualize sensitivity analysis results in Excel: graphing and '
                        'conditional formatting.',
                        'Graphing is usually appropriate for one-way data tables',
                        'Conditional formatting is usually appropriate for two-way data tables'
                    ],
                    title='Visualizing Sensitivity Analysis in Excel'
                ),
                lp.GraphicFrame(
                    images_path('excel-conditional-formatting.png'),
                    title='Conditional Formatting in Excel'
                ),
                InClassExampleFrame(
                    [
                        'I will now go through adding sensitivity analysis to the Dynamic Salary Retirement Model '
                        'in Excel',
                        'The completed exercise on the course site, '
                        '"Dynamic Salary Retirement Model Sensitivity.xlsx"'
                    ],
                    title='Sensitivity Analysis in Excel',
                    block_title='Adding Sensitivity Analysis to the Dynamic Retirement Excel Model'
                ),
                sensitivity_excel_lab.presentation_frames(),
            ],
            title='Sensitivity Analysis in Excel with Data Tables',
            short_title='SA Excel'
        ),
        pl.Section(
            [
                lp.Frame(
                    [
                        "We'll cover a couple more Python patterns and a new data type before jumping into sensitivity analysis",
                        pl.UnorderedList([
                            'Dictionaries',
                            'List comprehensions',
                            ['Python', import_mono, 'system and custom code']
                        ])
                    ],
                    title=f'Going Deeper into Python Code Structure'
                ),
                lp.TwoColumnGraphicDimRevealFrame(
                    [
                        ['A dictionary, or', dict_mono,
                         'for short, is another basic Python data type like lists, numbers, and strings.'],
                        'Like a list, it is a collection: it holds other objects.',
                        ['Unlike a list, a', dict_mono,
                         'is composed of key-value pairs. It holds relationships between objects.']
                    ],
                    graphics=[
                        lg.ModifiedPicture(
                            images_path('dictionary-book.jpg'),
                            draw_items=[
                                lg.Path('draw', [(0.5, 0.5)], draw_type='circle',
                                        options=['radius=0.4', 'red', 'line width=5mm']),
                                lg.Path('draw', [(0.2, 0.75), (0.8, 0.2)], draw_type='--',
                                        options=['red', 'line width=5mm'])
                            ]
                        )
                    ],
                    title='What is a Dictionary?'
                ),
                lp.Frame(
                    [
                        lp.Block(
                            [
                                pl.TextSize(-2),
                                dict_example,
                                *dict_printout_output
                            ],
                            title='Basic Dictionary Example'
                        )
                    ],
                    title='How to Use Dictionaries'
                ),
                lp.Frame(
                    [
                        lp.Block(
                            [
                                dict_example_2,
                            ],
                            title='Add and Delete Items from Dictionaries'
                        )
                    ],
                    title='How to Modify Dictionaries'
                ),
                InClassExampleFrame(
                    [
                        'I will now start going through the example notebook called '
                        '"Python Dicts, List comprehensions, and Imports.ipynb"',
                        'I will go through the Dictionaries section for now'
                    ],
                    title='More About Dictionaries in Python',
                    block_title='Using Dictionaries'
                ),
                dictionaries_lab.presentation_frames(),
                lp.Frame(
                    [
                        pl.TextSize(-1),
                        lp.Block(
                            [
                                list_comprehension_ex_1
                            ],
                            title=f'The Original Way'
                        ),
                        lp.Block(
                            [
                                list_comprehension_ex_2
                            ],
                            title=f'With List Comprehension'
                        ),
                        lp.Block(
                            ['You', pl.Bold('never'),
                             'need to use list comprehension, it is just for convenience. The original', for_mono,
                             'loop syntax will always work fine.'],
                            title='Notice'
                        )
                    ],
                    title=f"An Easier way to Build Simple Lists from Loops"
                ),
                InClassExampleFrame(
                    [
                        'I will continue going through the example notebook '
                        '"Python Dicts, List comprehensions, and Imports.ipynb"',
                        'I will go through the List Comprehensions section for now'
                    ],
                    title='Easier Loops in Python',
                    block_title='Using List Comprehensions'
                ),
                list_comp_lab.presentation_frames(),
                lp.DimRevealListFrame(
                    [
                        ['In the past we have used', import_mono, 'to load packages such as', np_mono, 'and', pd_mono],
                        ['These packages are just Python files. We can also write our own Python files and',
                         import_mono,
                         'them the same way'],
                        [f'When you {import_something_mono}, Python first searches the current directory for a file',
                         something_file, "and if it doesn't find it, it searches your installed packages"],
                        ['In fact if you added a', numpy_file, 'in the current directory and tried to', import_mono,
                         np_mono,
                         'it would', import_mono, 'the contents of that file rather than the', np_mono, 'package.']
                    ],
                    title=f'Understanding Python {import_mono}s'
                ),
                lp.DimRevealListFrame(
                    [
                        ['You can write your own functions and classes, then put them in a Python file and',
                         import_mono,
                         'them into your notebook.'],
                        ['When you', import_mono,
                         'a file, it executes the contents of that file. So you generally want just '
                         'function and class definitions, and not really anything outside of', def_mono, 'or',
                         class_mono,
                         'statements.'],
                        'Using Python files is a more maintainable structure for building complex models and apps versus '
                        'Jupyter notebooks only.'
                    ],
                    title='Importing Custom Code'
                ),
                lp.DimRevealListFrame(
                    [
                        'Sometimes you will need a package which does not already come installed with Anaconda',
                        ['The general way to do this is with', pip_install_mypackage, 'replacing mypackage with',
                         'the package you want to install'],
                        ['You would run this in Anaconda Prompt, or in Jupyter you can run it but you need to put an '
                        'exclaimation mark before it to say you want to run it in a terminal. So in Jupyter it would be',
                        jupyter_install_mypackage]
                    ],
                    title='Installing Packages'
                ),
                InClassExampleFrame(
                    [
                        'I will continue going through the example notebook '
                        '"Python Dicts, List comprehensions, and Imports.ipynb"',
                        'I will go through the Imports and Installing Packages section for now'
                    ],
                    title='Installing Packages in Python',
                    block_title='How to Install Packages'
                ),

            ],
            title='Python List Comprehensions, Installing Packages, and More on Dictionaries',
            short_title='Extra Python Basics'
        ),
        pl.Section(
            [
                lp.GraphicFrame(
                    images_path('python-sensitivity-hex-bins.pdf'),
                    title='Sensitivity Analysis in Python - Hex-Bin'
                ),
                lp.GraphicFrame(
                    images_path('sensitivity-analysis-styled-df.png'),
                    title='Sensitivity Analysis in Python - Styled DataFrame'
                ),
                lp.DimRevealListFrame(
                    [
                        'Generally, to do sensitivity analysis in Python without any special tools, you would just '
                        'create one nested for loop for each input, and finally within all the loops, run your model '
                        'with the inputs from the loops',
                        'This will work fine, but you will have many nested loops which can become hard to read. Also '
                        'it is a fair bit of setup involved.',
                        ['You can avoid the nested loops with', itertools_product, 'but then this becomes more '
                         'difficult to use and read']

                    ],
                    title='How to Do Sensitivity Analysis in Python (The Hard Way)'
                ),
                lp.Frame(
                    [
                        pl.TextSize(-3),
                        pl.UnorderedList([
                            'Say you have a function which runs your model, called model, which takes inputs of '
                            'inp1 and inp2'
                        ]),
                        lp.Block(
                            [
                                plain_sensitivity_example,
                                pl.Graphic(images_path('plain-sensitivity-result.png'), width=0.2),
                            ],
                            title='Sensitivity Analysis in Python with No Libraries'
                        )
                    ],
                    title='Sensitivity Analysis Example (Hard Way)'
                ),
                lp.DimRevealListFrame(
                    [
                        "When I first created this course, I thought there should be a good sensitivity analysis "
                        "tool in Python and I couldn't find it",
                        "The beauty of Python is if you want a tool that doesn't exist, you can create it, and "
                        "share it with others so that nobody else has to deal with the problem.",
                        ['So I created', sensitivity, 'a package for sensitivity analysis in Python, '
                                                      'which makes it very easy']

                    ],
                    title='How to Do Sensitivity Analysis in Python (The Easy Way)'
                ),
                lp.Frame(
                    [
                        pl.TextSize(-3),
                        pl.UnorderedList([
                            'Say you have a function which runs your model, called model, which takes inputs of '
                            'inp1 and inp2'
                        ]),
                        lp.Block(
                            [
                                easy_sensitivity_example,
                                pl.Graphic(images_path('plain-sensitivity-result.png'), width=0.2),
                            ],
                            title=f'Sensitivity Analysis in Python with {sensitivity}'
                        )
                    ],
                    title='Sensitivity Analysis Example (Easy Way)'
                ),
                InClassExampleFrame(
                    [
                        'I will now go through Sensitivity Analysis example Jupyter notebook',
                        'This notebook shows both the standard approach and using the sensitivity package',
                    ],
                    title='Intro to Sensitivity Analysis in Python',
                    block_title='An Overview of the Manual and Automated Approaches'
                ),
                InClassExampleFrame(
                    [
                        'I will now go through adding sensitivity analysis to the Dynamic Salary Retirement Model '
                        'in Python',
                        'The completed exercise available on the course site is called '
                        '"Dynamic Salary Retirement Model Sensitivity.ipynb"'
                    ],
                    title='Applying Sensitivity Analysis in Python',
                    block_title='Adding Sensitivity Analysis to the Dynamic Retirement Python Model'
                ),
                sensitivity_python_lab.presentation_frames(),
            ],
            title='Sensitivity Analysis in Python',
            short_title='SA Python'
        ),
        pl.PresentationAppendix(appendix_frames),
    ]
Example #5
0
def get_content():
    random.seed(1000)
    site_link = Hyperlink(SITE_URL, 'the course site')
    lecture = get_getting_started_with_python_and_excel_lecture()

    full_fix = Monospace('\$A\$2')
    col_fix = Monospace('\$A2')
    row_fix = Monospace('A\$2')
    notebook = Monospace('jupyter notebook')
    lab = Monospace('jupyter lab')
    list_ = Monospace('list')
    for_ = Monospace('for')
    append = Monospace('append')
    numpy = Monospace('numpy')
    cmd = Monospace('cmd')
    terminal = Monospace('terminal')
    in_block = Monospace('In [ ]:')
    numpy_financial = pl.Monospace('numpy_financial')

    example_python_iteration = Block(
        Python("""
inputs = [5, 10, 15]
for item in inputs:
    new_value = item + 2
    print(new_value)

7
12
17
        """),
        title='Python Iteration'
    )
    return [
        pl.Section(
            [
                TwoColumnGraphicDimRevealFrame(
                    [
                        'The focus today is to get familiar working in both Excel and Python',
                        'We will approach this by building a simple model with both tools',
                        'In later lectures, we will move to combining the tools'
                    ],
                    graphics=[
                        images_path('equations-chalkboard.jpg')
                    ],
                    title='Approaching a Problem with Two Tools'
                ),
                DimRevealListFrame(
                    [
                        "Let's take what is perhaps the simplest finance problem, which everyone should understand",
                        "While you may have approached such a problem with a calculator before, we will build models for it instead",
                        "Martha is saving for retirement. She earns \$60,000 per year and is able to save 25% of that. If she invests "
                        "her savings, earning 5% per year, and she needs \$1,500,000 to retire, how soon can she retire?"
                    ],
                    title='A Simple Retirement Problem'
                ),
                ModelFlowchartFrame(
                    [
                        [
                            'Wages, Savings',
                            'Investment',
                            Node('Cash in the bank, person retires',
                                 options=real_world_style + ['text width=2.5cm'])
                        ],
                        [
                            Node('Cash Flows, Savings Rate, Interest Rates',
                                 options=model_style + ['text width=3.5cm']),
                            'Model',
                            Node('FV of CF, time until retirement', options=model_style + ['text width=2.5cm'])
                        ]
                    ],
                    title='Breaking Down the Retirement Problem'
                ),
            ],
            title='An Introductory Model',
            short_title='Basic Problem'
        ),
        pl.Section(
            [
                TwoColumnGraphicDimRevealFrame(
                    [
                        "It is easy to use Excel as a calculator and just type the math in directly. But we want to build a model.",
                        "Changing inputs should result in a change to outputs. The way to do this in Excel is cell references",
                        rf"Fixed references become important when trying to drag formulas, e.g. {full_fix} (fully fixed), {col_fix} (fixed on "
                        rf"column), or {row_fix} (fixed on row)."
                    ],
                    graphics=[
                        images_path('excel-logo.png')
                    ],
                    title='Solving the Problem in Excel'
                ),
                InClassExampleFrame(
                    [
                        ['Go to', site_link, 'and download Simple Retirement Model Excel'],
                        'Follow along as I recreate the simple model.'
                    ],
                    title='Simple Retirement Problem in Excel',
                    block_title='Intro Excel Exercise'
                )
            ],
            title='Excel Solution'
        ),
        pl.Section(
            [
                TwoColumnGraphicDimRevealFrame(
                    [
                        pl.TextSize(-1),
                        "Using Python in the terminal is kind of a pain. And so, tools were born.",
                        "Jupyter is a graphical interface we can use for Python. It also supports over 40 other "
                        "languages such as R, SAS, Julia, and Scala",
                        f"You can use {notebook} or {lab}. The latter has a lot more features outside of the notebook. "
                        f"We will focus on using {lab} in this class as it is the future of Jupyter."
                    ],
                    graphics=[
                        images_path('jupyter-notebook.png')
                    ],
                    title="How We'll Work in Python"
                ),
                Frame(
                    [
                        LabBlock(
                            [
                                OrderedList([
                                    "Launch Anaconda Navigator",
                                    "Find Jupyter Notebook on the main screen, and click launch",
                                    "You should see a list of folders and files. Click New and then Python 3",
                                    f"Now you should see a code cell with {in_block} next to it"
                                ])
                            ],
                            title='Launch Jupyter Notebook'
                        ),
                        AlertBlock(
                            f"If you don't have Anaconda Navigator, just open a terminal (search {cmd} on Windows, {terminal} on Mac). Then in the "
                            f"terminal, type {lab} and enter. Then continue with the third step."
                        )
                    ],
                    title="Let's Get Set up with Jupyter"

                ),
                DimRevealListFrame(
                    [
                        "In Excel, the basic unit is a cell. In Python, the basic unit is an object.",
                        "In Excel, content in a cell is either a number (123) or a string (ABC)",
                        "In Python, all objects have types. They might also be a number or a string, or something else.",
                        f"Rather than using a cell reference like {full_fix}, we assign names to objects in Python",
                        Python("""
                        my_number = 6
                        my_string = 'ABC'
                        """)
                    ],
                    title='Some Python Basics'
                ),
                TwoColumnFrame(
                    [
                        pl.Graphic(images_path('numpy-logo.png')),
                        pl.Block(
                            [
                                pl.TextSize(-2),
                                'In the future, these numpy financial functions are being moved '
                                'to a separate package', f'{numpy_financial}.', 'For',
                                "the purposes of this class, this won't matter, but in the future you may have "
                                "to install", numpy_financial, 'to use these functions.',
                                'In the meantime, you will see a warning come up when calling the functions.'
                            ],
                            title='Note: Deprecation warning'
                        ),
                    ],
                    [
                        UnorderedList([
                            DimAndRevealListItems(
                                [
                                    "Basic operations in Python are straightforward",
                                    Python('2 + 5 = 7'),
                                    Python('6 - 2 = 4'),
                                    Python('2 * 3 = 6'),
                                    Python('5 / 2 = 2.5'),
                                    f'A lot more is available using the {numpy} package',
                                    Python("np.pv, np.nper,\nnp.fv, np.pmt"),
                                    Hyperlink(
                                        'https://numpy.org/doc/stable/reference/routines.financial.html',
                                        f'All numpy financial functions')
                                ],
                                dim_earlier_items=False
                            )
                        ])
                    ],
                    title='Doing Some Math in Python'
                ),
                InClassExampleFrame(
                    [
                        ['Go to', site_link, 'and download Simple Retirement Model Python'],
                        'In Jupyter, then navigate to your Downloads folder (or wherever you saved it)',
                        'You should then see Simple Retirement Model.ipynb come up in the list of files in Jupyter. '
                        'Click it to open it and follow along.'
                    ],
                    title='Simple Retirement Problem in Python',
                    block_title='Intro Python Exercise'
                )
            ],
            title='Python Solution'
        ),
        pl.Section(
            [
                DimRevealListFrame(
                    [
                        "Now we've got basic models to determine how long it will take Martha to retire.",
                        "We've got a few assumptions built into the model. One is that Martha will earn 5% on her investments",
                        "Rates of return are volatile, so we want to see how long it would take her to retire if her return was different"
                    ],
                    title='Extending the Model - Multiple Interest Rates'
                ),
                DimRevealListFrame(
                    [
                        "In programming, for model building or otherwise, you often need to repeat the same process for multiple different things",
                        "In Excel, you would do this by dragging formulas.",
                        f"In Python, as in most other programming languages, we would use a {for_} loop",
                        "This says, do something, for each value I pass into the loop"
                    ],
                    title='Programming Fundamentals - Iteration'
                ),
                BasicTwoColumnFrame(
                    [
                        example_python_iteration
                    ],
                    [
                        Block(
                            Graphic(
                                images_path('excel-iteration.png')
                            ),
                            title='Excel Iteration'
                        )
                    ],
                    title='Iteration - Python vs. Excel'
                ),
                TwoColumnFrame(
                    [
                        UnorderedList([
                            DimAndRevealListItems([
                                "There's a few things to unpack here",
                                f"Here's another type of object: not a number or a string, but a {list_}",
                                f"A {list_} holds multiple objects, and you can add or remove items from {list_}s",
                            ])
                        ])
                    ],
                    [
                        example_python_iteration
                    ],
                    title='Explaining Python Iteration'
                ),
                TwoColumnFrame(
                    [
                        UnorderedList([
                            DimAndRevealListItems([
                                "Here we define a list of three numbers as inputs",
                                f"Then we use a {for_} loop to get each input out of the list, and add 2 to it to create the new value",
                                "Finally we print each value as it is generated"
                            ])
                        ])
                    ],
                    [
                        example_python_iteration
                    ],
                    title='Explaining Python Iteration (pt. 2)'
                ),
                InClassExampleFrame(
                    [
                        'I will now expand the existing Excel and Python models to examine multiple interest rates',
                        'Continue viewing the same previously downloaded files.'
                    ],
                    title='Iterating the Existing Model',
                    block_title='Expanding on Python and Excel'
                ),
                get_simple_retirement_lab_lecture().to_pyexlatex().presentation_frames(),
            ],
            title='Extending the Model and Iteration',
            short_title='Extend & Iterate'
        ),
        pl.PresentationAppendix(
            [
                lecture.pyexlatex_resources_frame,
                pl.TextSize(-1),
                get_simple_retirement_lab_lecture().to_pyexlatex().appendix_frames(),
                pl.TextSize(0),
            ]
        )
    ]
         pl.Equation(str_eq=default_prob_eq_str, inline=False),
         problem_definition_post_prob
     ],
                   title='Problem Definition'),
     pl.SubSection([main_q_str], title='Main Question'),
     pl.SubSection([pl.UnorderedList(notes)], title='Notes'),
     pl.SubSection([inputs_content], title='Inputs'),
     pl.SubSection([bonus_q_str], title='Bonus Question'),
 ],
            title='Overview'),
 pl.Section([
     pl.SubSection([submission_str], title='Submission'),
     pl.SubSection([
         solutions_str,
         pl.Center(
             pl.Graphic(images_path('project-2-solutions.png'),
                        width=0.5), ),
         case_solutions_str,
         pl.UnorderedList(case_solutions_list),
     ],
                   title='Selected Solutions'),
     pl.SubSection([
         pl.Center(
             lt.Tabular([
                 lt.MultiColumnLabel('Grading Breakdown', span=2),
                 lt.TopRule(),
                 lt.ValuesTable.from_list_of_lists(
                     [['Category', 'Percentage']]),
                 lt.TableLineSegment(0, 1),
                 lt.ValuesTable.from_list_of_lists([
                     ['Model Accuracy', '60%'],
                     ['Model Readability', '20%'],
Example #7
0
def test_graphic_from_single_graphic_figure():
    graphic = pl.Graphic(str(EXAMPLE_IMAGE_PATH))
    fig = pl.Figure([graphic])
    graphics = fig.to_graphic_list()
    assert str(graphic) == str(graphics[0])
    assert len(graphics) == 1
Example #8
0
def get_series_example_frames():
    pd_mono = pl.Monospace('pandas')
    series_mono = pl.Monospace('Series')
    df_mono = pl.Monospace('DataFrame')

    series_ex_1 = pl.Python("""
>>> df = pd.DataFrame()
>>> df['Numbers'] = [1, 2, 3]
>>> df['Categories'] = ['apple', 'apple', 'orange']
>>> df
""")
    series_ex_2 = pl.Python("""
>>> df['Categories']
0     apple
1     apple
2    orange
Name: Categories, dtype: object
>>> type(df['Categories'])
pandas.core.series.Series
""")
    series_ex_3 = pl.Python("""
>>> cats = df['Categories']
>>> cats
0     apple
1     apple
2    orange
Name: Categories, dtype: object
>>> cats[2]
'orange'
>>> cats.index = ['a', 'b', 'c']
>>> cats
a     apple
b     apple
c    orange
Name: Categories, dtype: object
>>> cats['b']
'apple'
""")
    return [
        lp.DimRevealListFrame([[
            'A', series_mono, 'is the other main', pd_mono,
            'data type besides a', df_mono
        ], [
            'A single column or row of a', df_mono, 'is a', series_mono
        ], ['A', series_mono, 'has a name, an index, and one value per index']
                               ],
                              title=f'What is a {series_mono}?'),
        lp.Frame([
            lp.Block([
                series_ex_1,
                pl.Graphic(images_path('series-example-df.png'), width=0.2),
                series_ex_2
            ],
                     title=f'{series_mono} Example')
        ],
                 title=f"{df_mono}s are Made up of {series_mono}'"),
        lp.Frame(
            [
                lp.Block([
                    pl.TextSize(-1),
                    series_ex_3,
                ],
                         title=f'Working with {series_mono} Example')
            ],
            title=f"Access {series_mono} Values Just Like {df_mono} Columns")
    ]
Example #9
0
def get_content():
    random.seed(1000)

    lecture = get_visualization_lecture()
    intro_pandas_lab = get_intro_to_pandas_lab_lecture().to_pyexlatex()
    styling_pandas_lab = get_pandas_styling_lab_lecture().to_pyexlatex()
    graphing_lab = get_intro_python_visualization_lab_lecture().to_pyexlatex()
    appendix_frames = [
        lecture.pyexlatex_resources_frame,
        intro_pandas_lab.appendix_frames(),
        styling_pandas_lab.appendix_frames(),
        graphing_lab.appendix_frames()
    ]

    ret_model = RetirementModel()
    ret_df = ret_model.get_formatted_df(num_years=12)
    ret_table = lt.Tabular.from_df(ret_df, extra_header=pl.Bold('Retirement Info'))
    plt_mono = pl.Monospace('matplotlib')
    df_mono = pl.Monospace('DataFrame')
    df_basic_example = pl.Python(
"""
>>> import pandas as pd
>>> df = pd.DataFrame()
>>> df['Sales'] = [1052, 212, 346]
>>> df['Category'] = ['Aprons', 'Apples', 'Bowties']
df
"""
    )
    plot_example_code = pl.Python(
"""
>>> %matplotlib inline
>>> ret_df.plot.line(x='Time', y='Salaries')
"""
    )

    return [
        pl.Section(
            [
                lp.DimRevealListFrame(
                    [
                        "So far we've had one main output from our model, number of years",
                        "Salaries and wealth over time have also been outputs, but we haven't had a good way of understanding "
                        "that output. It's a bunch of numbers.",
                        "This is where visualization comes in. We have some complex result, and want to make it easily "
                        "interpretable."
                    ],
                    title='Why Visualize?'
                ),
                lp.Frame(
                    [
                        pl.Center(ret_table)
                    ],
                    title='What we Have so Far'
                ),
                lp.GraphicFrame(
                    images_path('excel-insert-chart.png'),
                    title='Visualization in Excel'
                ),
                lp.GraphicFrame(
                    lg.ModifiedPicture(
                        images_path('python-visualization-landscape.jpg'),
                        [
                            lg.Path('draw', [(0.52, 0.52), (0.85, 0.67)], options=['red'], draw_type='rectangle',
                                    overlay=lp.Overlay([2]))
                        ]
                    ),
                    title='An Overwhelming Number of Options in Python'
                ),
                lp.DimRevealListFrame(
                    [
                        ["Ultimately, we will be creating graphs using", plt_mono, "but we won't use it directly."],
                        ["Instead, we will use", pd_mono],
                        [pd_mono, "is actually creating its graphs using", plt_mono,
                         "for us, but it is simpler to use."]
                    ],
                    title='Explaining Python Visualization in This Class'
                ),
                InClassExampleFrame(
                    [
                        'I will now go back to the "Dynamic Salary Retirement Model.xlsx" Excel model to '
                        'add visualization',
                        'I have also uploaded the completed workbook from this exercise '
                        'as "Dynamic Salary Retirement Model Visualized.xlsx"',
                        'Follow along as I go through the example.',
                    ],
                    title='Visualization in Excel',
                    block_title='Adding Graphs to the Dynamic Salary Retirement Excel Model'
                ),

            ],
            title='Visualization Introduction',
            short_title='Intro'
        ),
        pl.Section(
            [
                lp.DimRevealListFrame(
                    [
                        [pd_mono, "does", pl.Bold('a lot'), 'more than just graphing. We will use it throughout the '
                                                            'rest of the class.'],
                        "Previously we've worked with lists, numbers, strings, and even our custom types (our model dataclasses)",
                        [pd_mono, "provides the", df_mono, "as a new type that we can use."],
                        f'Before we can get to graphing, we must learn how to use the {df_mono}.'

                    ],
                    title='Some Setup Before we can Visualize in Python'
                ),
                lp.Frame(
                    [
                        ['A', df_mono, 'is essentially a table. It has rows and columns, just like in Excel.'],
                        pl.VFill(),
                        lp.Block(
                            [
                                pl.UnorderedList([
                                    'Add or remove columns or rows',
                                    'Group by and aggregate',
                                    'Load in and output data from/to Excel and many other formats',
                                    'Merge and join data sets',
                                    'Reshape and pivot data',
                                    'Time-series functionality',
                                    'Slice and query your data',
                                    'Handle duplicates and missing data'
                                ])
                            ],
                            title=f'Some Features of the {df_mono}'
                        )

                    ],
                    title=f'What is a {df_mono}?'
                ),
                lp.Frame(
                    [
                        df_basic_example,
                        pl.Graphic(images_path('df-basic-example.png'), width=0.3)

                    ],
                    title=f'A Basic {df_mono} Example'
                ),
                InClassExampleFrame(
                    [
                        'I will now go through the notebook in '
                        '"Intro to Pandas and Table Visualization.ipynb"',
                        'Follow along as I go through the example.',
                        'We will complete everything up until DataFrame Styling'
                    ],
                    title='Introduction to Pandas',
                    block_title='Creating and Using Pandas DataFrames'
                ),
                intro_pandas_lab.presentation_frames(),
                lp.DimRevealListFrame(
                    [
                        ['It is possible to add styling to our displayed tabular data by styling the', df_mono],
                        'The styling is very flexible and essentially allows you to do anything',
                        'Out of the box, it is easy to change colors, size, and positioning of text, add a caption, do '
                        'conditional formatting, and draw a bar graph over the cells.'
                    ],
                    title='Styling Pandas DataFrames'
                ),
                InClassExampleFrame(
                    [
                        'I will now go through the next section in '
                        '"Intro to Pandas and Table Visualization.ipynb"',
                        'Follow along as I go through the example.',
                        'This time we are covering the remainder of the notebook starting from "DataFrame Styling"'
                    ],
                    title='Introduction to Pandas',
                    block_title='Creating and Using Pandas DataFrames'
                ),
                styling_pandas_lab.presentation_frames(),
            ],
            title='Tables with Pandas DataFrames',
            short_title='Pandas'
        ),
        pl.Section(
            [
                lp.Frame(
                    [
                        lp.Block(
                            [
                                plot_example_code,
                                pl.Graphic(images_path('python-salaries-line-graph.pdf'), width=0.5)
                            ],
                            title=f'Line Graphs using {pd_mono}'
                        )
                    ],
                    title='A Minimal Plotting Example'
                ),
                lp.MultiGraphicFrame(
                    [
                        images_path('excel-salaries-line-graph.png'),
                        images_path('python-salaries-line-graph.pdf'),
                    ],
                    vertical=False,
                    title='Basic Graph Types: Line Graphs'
                ),
                lp.MultiGraphicFrame(
                    [
                        images_path('excel-salaries-bar-graph.png'),
                        images_path('python-salaries-bar-graph.pdf'),
                    ],
                    vertical=False,
                    title='Basic Graph Types: Bar Graphs'
                ),
                lp.MultiGraphicFrame(
                    [
                        images_path('excel-salaries-box-whisker-plot.png'),
                        images_path('python-salaries-box-graph.pdf'),
                    ],
                    vertical=False,
                    title='Basic Graph Types: Box and Whisker Plots'
                ),
                InClassExampleFrame(
                    [
                        'I will now go through '
                        '"Intro to Graphics.ipynb"',
                        'Follow along as I go through the entire example notebook.',
                    ],
                    title='Introduction to Graphing',
                    block_title='Graphing Using Pandas'
                ),
                graphing_lab.presentation_frames(),
            ],
            title='Graphing using Pandas',
            short_title='Graphs'
        ),
        pl.PresentationAppendix(appendix_frames)
    ]