示例#1
0
def test_macro_table(base_tpi, base_params, reform_tpi, reform_params,
                     output_type):
    df = output_tables.macro_table(
        base_tpi, base_params, reform_tpi=reform_tpi,
        reform_params=reform_params, output_type=output_type,
        include_SS=True, include_overall=True)
    assert isinstance(df, pd.DataFrame)
示例#2
0
def run_micro_macro(og_spec, guid, client):

    guid = ''
    start_time = time.time()

    REFORM_DIR = os.path.join(CUR_PATH, "OUTPUT_REFORM_" + guid)
    BASELINE_DIR = os.path.join(CUR_PATH, "OUTPUT_BASELINE" + guid)

    with open("log_{}.log".format(guid), 'w') as f:
        f.write("guid: {}\n".format(guid))
        f.write("og_spec: {}\n".format(og_spec))

    '''
    ------------------------------------------------------------------------
        Run baseline
    ------------------------------------------------------------------------
    '''
    p = Specifications(
        baseline=True, num_workers=NUM_WORKERS,
        baseline_dir=BASELINE_DIR, output_base=BASELINE_DIR)
    p.update_specifications(og_spec)
    runner(p, time_path=True, client=client)

    '''
    ------------------------------------------------------------------------
        Run reform
    ------------------------------------------------------------------------
    '''
    p = Specifications(
        baseline=False, num_workers=NUM_WORKERS,
        baseline_dir=BASELINE_DIR, output_base=REFORM_DIR)
    p.update_specifications(og_spec)
    runner(p, time_path=True, client=client)
    time.sleep(0.5)
    base_tpi = safe_read_pickle(
        os.path.join(BASELINE_DIR, 'TPI', 'TPI_vars.pkl'))
    base_params = safe_read_pickle(
        os.path.join(BASELINE_DIR, 'model_params.pkl'))
    reform_tpi = safe_read_pickle(
        os.path.join(REFORM_DIR, 'TPI', 'TPI_vars.pkl'))
    reform_params = safe_read_pickle(
        os.path.join(REFORM_DIR, 'model_params.pkl'))
    ans = ot.macro_table(
        base_tpi, base_params, reform_tpi=reform_tpi,
        reform_params=reform_params,
        var_list=['Y', 'C', 'K', 'L', 'r', 'w'], output_type='pct_diff',
        num_years=10, start_year=base_params.start_year)
    print("total time was ", (time.time() - start_time))

    return ans
示例#3
0
def comp_output(
    base_params,
    base_ss,
    reform_params,
    reform_ss,
    time_path,
    base_tpi=None,
    reform_tpi=None,
    var="cssmat",
):
    """
    Function to create output for the COMP platform
    """
    if time_path:
        table_title = "Percentage Changes in Economic Aggregates Between"
        table_title += " Baseline and Reform Policy"
        plot1_title = "Pct Changes in Economic Aggregates Between"
        plot1_title += " Baseline and Reform Policy"
        plot2_title = "Pct Changes in Interest Rates and Wages"
        plot2_title += " Between Baseline and Reform Policy"
        plot3_title = "Differences in Fiscal Variables Relative to GDP"
        plot3_title += " Between Baseline and Reform Policy"
        out_table = ot.tp_output_dump_table(
            base_params,
            base_tpi,
            reform_params,
            reform_tpi,
            table_format="csv",
        )
        html_table = ot.macro_table(
            base_tpi,
            base_params,
            reform_tpi,
            reform_params,
            var_list=["Y", "C", "I_total", "L", "D", "G", "r", "w"],
            output_type="pct_diff",
            num_years=10,
            include_SS=True,
            include_overall=True,
            start_year=base_params.start_year,
            table_format="html",
        )
        fig1 = op.plot_aggregates(
            base_tpi,
            base_params,
            reform_tpi,
            reform_params,
            var_list=["Y", "C", "K", "L"],
            plot_type="pct_diff",
            num_years_to_plot=50,
            start_year=base_params.start_year,
            vertical_line_years=[
                base_params.start_year + base_params.tG1,
                base_params.start_year + base_params.tG2,
            ],
            plot_title=None,
            path=None,
        )
        in_memory_file1 = io.BytesIO()
        fig1.savefig(in_memory_file1, format="png", bbox_inches="tight")
        in_memory_file1.seek(0)
        fig2 = op.plot_aggregates(
            base_tpi,
            base_params,
            reform_tpi,
            reform_params,
            var_list=["r_gov", "w"],
            plot_type="pct_diff",
            num_years_to_plot=50,
            start_year=base_params.start_year,
            vertical_line_years=[
                base_params.start_year + base_params.tG1,
                base_params.start_year + base_params.tG2,
            ],
            plot_title=None,
            path=None,
        )
        in_memory_file2 = io.BytesIO()
        fig2.savefig(in_memory_file2, format="png", bbox_inches="tight")
        in_memory_file2.seek(0)
        fig3 = op.plot_gdp_ratio(
            base_tpi,
            base_params,
            reform_tpi,
            reform_params,
            var_list=["D", "G", "total_tax_revenue"],
            plot_type="diff",
            num_years_to_plot=50,
            start_year=base_params.start_year,
            vertical_line_years=[
                base_params.start_year + base_params.tG1,
                base_params.start_year + base_params.tG2,
            ],
            plot_title=None,
            path=None,
        )
        in_memory_file3 = io.BytesIO()
        fig3.savefig(in_memory_file3, format="png", bbox_inches="tight")
        in_memory_file3.seek(0)

        comp_dict = {
            "renderable": [
                {
                    "media_type": "PNG",
                    "title": plot1_title,
                    "data": in_memory_file1.read(),
                },
                {
                    "media_type": "PNG",
                    "title": plot2_title,
                    "data": in_memory_file2.read(),
                },
                {
                    "media_type": "PNG",
                    "title": plot3_title,
                    "data": in_memory_file3.read(),
                },
                {
                    "media_type": "table",
                    "title": table_title,
                    "data": html_table,
                },
            ],
            "downloadable": [
                {
                    "media_type": "CSV",
                    "title": table_title,
                    "data": out_table.to_csv(),
                }
            ],
        }
    else:
        table_title = "Percentage Changes in Economic Aggregates Between"
        table_title += " Baseline and Reform Policy"
        plot_title = "Percentage Changes in Consumption by Lifetime Income"
        plot_title += " Percentile Group"
        out_table = ot.macro_table_SS(
            base_ss,
            reform_ss,
            var_list=[
                "Yss",
                "Css",
                "Iss_total",
                "Gss",
                "total_tax_revenue",
                "Lss",
                "rss",
                "wss",
            ],
            table_format="csv",
        )
        html_table = ot.macro_table_SS(
            base_ss,
            reform_ss,
            var_list=[
                "Yss",
                "Css",
                "Iss_total",
                "Gss",
                "total_tax_revenue",
                "Lss",
                "rss",
                "wss",
            ],
            table_format="html",
        )
        fig = op.ability_bar_ss(
            base_ss, base_params, reform_ss, reform_params, var=var
        )
        in_memory_file = io.BytesIO()
        fig.savefig(in_memory_file, format="png", bbox_inches="tight")
        in_memory_file.seek(0)

        comp_dict = {
            "renderable": [
                {
                    "media_type": "PNG",
                    "title": plot_title,
                    "data": in_memory_file.read(),
                },
                {
                    "media_type": "table",
                    "title": table_title,
                    "data": html_table,
                },
            ],
            "downloadable": [
                {
                    "media_type": "CSV",
                    "title": table_title,
                    "data": out_table.to_csv(),
                }
            ],
        }

    return comp_dict
示例#4
0
def main():
    # Define parameters to use for multiprocessing
    client = Client()
    num_workers = min(multiprocessing.cpu_count(), 7)
    print("Number of workers = ", num_workers)

    # Directories to save data
    CUR_DIR = os.path.dirname(os.path.realpath(__file__))
    base_dir = os.path.join(CUR_DIR, "OG-USA-Example", "OUTPUT_BASELINE")
    reform_dir = os.path.join(CUR_DIR, "OG-USA-Example", "OUTPUT_REFORM")
    """
    ------------------------------------------------------------------------
    Run baseline policy
    ------------------------------------------------------------------------
    """
    # Set up baseline parameterization
    p = Specifications(
        baseline=True,
        num_workers=num_workers,
        baseline_dir=base_dir,
        output_base=base_dir,
    )
    # Update parameters for baseline from default json file
    p.update_specifications(
        json.load(
            open(
                os.path.join(CUR_DIR, "..", "ogusa",
                             "ogusa_default_parameters.json"))))

    # Run model
    start_time = time.time()
    runner(p, time_path=True, client=client)
    print("run time = ", time.time() - start_time)
    """
    ------------------------------------------------------------------------
    Run reform policy
    ------------------------------------------------------------------------
    """
    # Grab a reform JSON file already in Tax-Calculator
    # In this example the 'reform' is a change to 2017 law (the
    # baseline policy is tax law in 2018)
    reform_url = ("github://*****:*****@main/psl_examples/" +
                  "taxcalc/2017_law.json")
    ref = Calculator.read_json_param_objects(reform_url, None)
    iit_reform = ref["policy"]

    # create new Specifications object for reform simulation
    p2 = Specifications(
        baseline=False,
        num_workers=num_workers,
        baseline_dir=base_dir,
        output_base=reform_dir,
    )
    # Update parameters for baseline from default json file
    p2.update_specifications(
        json.load(
            open(
                os.path.join(CUR_DIR, "..", "ogusa",
                             "ogusa_default_parameters.json"))))
    # Use calibration class to estimate reform tax functions from
    # Tax-Calculator, specifing reform for Tax-Calculator in iit_reform
    c2 = Calibration(p2,
                     iit_reform=iit_reform,
                     estimate_tax_functions=True,
                     client=client)
    # update tax function parameters in Specifications Object
    d = c2.get_dict()
    # additional parameters to change
    updated_params = {
        "cit_rate": [0.35],
        "etr_params": d["etr_params"],
        "mtrx_params": d["mtrx_params"],
        "mtry_params": d["mtry_params"],
        "mean_income_data": d["mean_income_data"],
        "frac_tax_payroll": d["frac_tax_payroll"],
    }
    p2.update_specifications(updated_params)
    # Run model
    start_time = time.time()
    runner(p2, time_path=True, client=client)
    print("run time = ", time.time() - start_time)
    client.close()
    """
    ------------------------------------------------------------------------
    Save some results of simulations
    ------------------------------------------------------------------------
    """
    base_tpi = safe_read_pickle(os.path.join(base_dir, "TPI", "TPI_vars.pkl"))
    base_params = safe_read_pickle(os.path.join(base_dir, "model_params.pkl"))
    reform_tpi = safe_read_pickle(
        os.path.join(reform_dir, "TPI", "TPI_vars.pkl"))
    reform_params = safe_read_pickle(
        os.path.join(reform_dir, "model_params.pkl"))
    ans = ot.macro_table(
        base_tpi,
        base_params,
        reform_tpi=reform_tpi,
        reform_params=reform_params,
        var_list=["Y", "C", "K", "L", "r", "w"],
        output_type="pct_diff",
        num_years=10,
        start_year=base_params.start_year,
    )

    # create plots of output
    op.plot_all(base_dir, reform_dir,
                os.path.join(CUR_DIR, "OG-USA_example_plots"))

    print("Percentage changes in aggregates:", ans)
    # save percentage change output to csv file
    ans.to_csv("ogusa_example_output.csv")
示例#5
0
def main():
    # Define parameters to use for multiprocessing
    client = Client()
    num_workers = min(multiprocessing.cpu_count(), 7)
    print('Number of workers = ', num_workers)
    run_start_time = time.time()

    # Directories to save data
    CUR_DIR = os.path.dirname(os.path.realpath(__file__))
    base_dir = os.path.join(CUR_DIR, BASELINE_DIR)
    reform_dir = os.path.join(CUR_DIR, REFORM_DIR)

    # Set some OG model parameters
    # See default_parameters.json for more description of these parameters
    alpha_T = np.zeros(50)  # Adjusting the path of transfer spending
    alpha_T[0:2] = 0.09
    alpha_T[2:10] = 0.09 + 0.01
    alpha_T[10:40] = 0.09 - 0.01
    alpha_T[40:] = 0.09
    alpha_G = np.zeros(7)  # Adjusting the path of non-transfer spending
    alpha_G[0:3] = 0.05 - 0.01
    alpha_G[3:6] = 0.05 - 0.005
    alpha_G[6:] = 0.05
    # Set start year for baseline and reform.
    START_YEAR = 2021
    # Also adjust the Frisch elasticity, the start year, the
    # effective corporate income tax rate, and the SS debt-to-GDP ratio
    og_spec = {
        'frisch': 0.41,
        'start_year': START_YEAR,
        'cit_rate': [0.21],
        'debt_ratio_ss': 1.0,
        'alpha_T': alpha_T.tolist(),
        'alpha_G': alpha_G.tolist()
    }
    '''
    ------------------------------------------------------------------------
    Run baseline policy first
    ------------------------------------------------------------------------
    '''
    p = Specifications(
        baseline=True,
        num_workers=num_workers,
        baseline_dir=base_dir,
        output_base=base_dir,
    )
    # Update parameters for baseline from default json file
    p.update_specifications(og_spec)

    start_time = time.time()
    runner(p, time_path=True, client=client)
    print('run time = ', time.time() - start_time)
    '''
    ------------------------------------------------------------------------
    Run reform policy
    ------------------------------------------------------------------------
    '''
    # update the effective corporate income tax rate
    og_spec.update({'cit_rate': [0.35]})
    p2 = Specifications(
        baseline=False,
        num_workers=num_workers,
        baseline_dir=base_dir,
        output_base=reform_dir,
    )
    # Update parameters for baseline from default json file
    p2.update_specifications(og_spec)

    start_time = time.time()
    runner(p2, time_path=True, client=client)
    print('run time = ', time.time() - start_time)

    # return ans - the percentage changes in macro aggregates and prices
    # due to policy changes from the baseline to the reform
    base_tpi = safe_read_pickle(os.path.join(base_dir, 'TPI', 'TPI_vars.pkl'))
    base_params = safe_read_pickle(os.path.join(base_dir, 'model_params.pkl'))
    reform_tpi = safe_read_pickle(
        os.path.join(reform_dir, 'TPI', 'TPI_vars.pkl'))
    reform_params = safe_read_pickle(
        os.path.join(reform_dir, 'model_params.pkl'))
    ans = ot.macro_table(base_tpi,
                         base_params,
                         reform_tpi=reform_tpi,
                         reform_params=reform_params,
                         var_list=['Y', 'C', 'K', 'L', 'r', 'w'],
                         output_type='pct_diff',
                         num_years=10,
                         start_year=og_spec['start_year'])

    # create plots of output
    op.plot_all(base_dir, reform_dir, os.path.join(CUR_DIR,
                                                   'run_example_plots'))

    print("total time was ", (time.time() - run_start_time))
    print('Percentage changes in aggregates:', ans)
    # save percentage change output to csv file
    ans.to_csv('ogcore_example_output.csv')
    client.close()
示例#6
0
def main(reform=None):
    if reform is None:
        reform = get_default_reform()
    # Define parameters to use for multiprocessing
    client = Client()
    num_workers = min(multiprocessing.cpu_count(), 7)
    print("Number of workers = ", num_workers)

    # Directories to save data
    CUR_DIR = os.path.dirname(os.path.realpath(__file__))
    base_dir = os.path.join(CUR_DIR, "OG-UK-Example", "OUTPUT_BASELINE")
    reform_dir = os.path.join(CUR_DIR, "OG-UK-Example", "OUTPUT_REFORM")
    """
    ------------------------------------------------------------------------
    Run baseline policy
    ------------------------------------------------------------------------
    """
    # Set up baseline parameterization
    p = Specifications(
        baseline=True,
        num_workers=num_workers,
        baseline_dir=base_dir,
        output_base=base_dir,
    )
    # Update parameters for baseline from default json file
    p.update_specifications(
        json.load(
            open(
                os.path.join(CUR_DIR, "..", "oguk",
                             "oguk_default_parameters.json"))))
    # specify tax function form and start year
    p.update_specifications({
        "tax_func_type": "DEP",
        "age_specific": False,
        "start_year": START_YEAR,
        "alpha_T": [5e-3],
        "alpha_G": [5e-3],
    })
    # Estimate baseline tax functions from OpenFisca-UK
    c = Calibration(p, estimate_tax_functions=True, client=client)
    # update tax function parameters in Specifications Object
    d = c.get_dict()
    updated_params = {
        "etr_params": d["etr_params"],
        "mtrx_params": d["mtrx_params"],
        "mtry_params": d["mtry_params"],
        "mean_income_data": d["mean_income_data"],
        "frac_tax_payroll": d["frac_tax_payroll"],
    }
    p.update_specifications(updated_params)
    # Run model
    start_time = time.time()
    runner(p, time_path=True, client=client)
    print("run time = ", time.time() - start_time)
    """
    ------------------------------------------------------------------------
    Run reform policy
    ------------------------------------------------------------------------
    """

    # create new Specifications object for reform simulation
    p2 = Specifications(
        baseline=False,
        num_workers=num_workers,
        baseline_dir=base_dir,
        output_base=reform_dir,
    )
    # Update parameters for baseline from default json file
    p2.update_specifications(
        json.load(
            open(
                os.path.join(CUR_DIR, "..", "oguk",
                             "oguk_default_parameters.json"))))
    # specify tax function form and start year
    p2.update_specifications({
        "tax_func_type": "DEP",
        "age_specific": False,
        "start_year": START_YEAR,
        "alpha_T": [5e-3],
        "alpha_G": [5e-3],
    })
    # Estimate reform tax functions from OpenFisca-UK, passing Reform
    # class object
    c2 = Calibration(p2,
                     iit_reform=reform,
                     estimate_tax_functions=True,
                     client=client)
    # update tax function parameters in Specifications Object
    d2 = c2.get_dict()
    updated_params2 = {
        "etr_params": d2["etr_params"],
        "mtrx_params": d2["mtrx_params"],
        "mtry_params": d2["mtry_params"],
        "mean_income_data": d2["mean_income_data"],
        "frac_tax_payroll": d2["frac_tax_payroll"],
    }
    p2.update_specifications(updated_params2)
    # Run model
    start_time = time.time()
    runner(p2, time_path=True, client=client)
    print("run time = ", time.time() - start_time)
    """
    ------------------------------------------------------------------------
    Save some results of simulations
    ------------------------------------------------------------------------
    """
    base_tpi = safe_read_pickle(os.path.join(base_dir, "TPI", "TPI_vars.pkl"))
    base_params = safe_read_pickle(os.path.join(base_dir, "model_params.pkl"))
    reform_tpi = safe_read_pickle(
        os.path.join(reform_dir, "TPI", "TPI_vars.pkl"))
    reform_params = safe_read_pickle(
        os.path.join(reform_dir, "model_params.pkl"))
    ans = ot.macro_table(
        base_tpi,
        base_params,
        reform_tpi=reform_tpi,
        reform_params=reform_params,
        var_list=["Y", "C", "K", "L", "r", "w"],
        output_type="pct_diff",
        num_years=10,
        start_year=base_params.start_year,
    )

    # create plots of output
    op.plot_all(base_dir, reform_dir,
                os.path.join(CUR_DIR, "OG-UK_example_plots"))

    print("Percentage changes in aggregates:", ans)
    # save percentage change output to csv file
    ans.to_csv("oguk_example_output.csv")
    client.close()