def main():
    guess = [0.92, 0.03]
    f_temp = lambda x: FagerengObjFunc(x[0], x[1])
    opt_params = minimizeNelderMead(f_temp, guess, verbose=True)
    print('Finished estimating for scaling factor of ' + str(AdjFactor) +
          ' and "splurge amount" of $' + str(1000 * Splurge))
    print('Optimal (beta,nabla) is ' + str(opt_params) +
          ', simulated MPCs are:')
    dist = FagerengObjFunc(opt_params[0], opt_params[1], True)
    print('Distance from Fagereng et al Table 9 is ' + str(dist))
Beispiel #2
0
def main():
    # Estimate the model using Nelder-Mead
    if estimate_model:
        initial_guess = [Params.DiscFacAdj_start, Params.CRRA_start]
        print(
            'Now estimating the model using Nelder-Mead from an initial guess of '
            + str(initial_guess) + '...')
        model_estimate = minimizeNelderMead(smmObjectiveFxnReduced,
                                            initial_guess,
                                            verbose=True)
        print('Estimated values: DiscFacAdj=' + str(model_estimate[0]) +
              ', CRRA=' + str(model_estimate[1]))

    # Compute standard errors by bootstrap
    if compute_standard_errors:
        std_errors = calculateStandardErrorsByBootstrap(
            model_estimate,
            N=Params.bootstrap_size,
            seed=Params.seed,
            verbose=True)
        print('Standard errors: DiscFacAdj--> ' + str(std_errors[0]) +
              ', CRRA--> ' + str(std_errors[1]))

    # Make a contour plot of the objective function
    if make_contour_plot:
        grid_density = 20  # Number of parameter values in each dimension
        level_count = 100  # Number of contour levels to plot
        DiscFacAdj_list = np.linspace(0.85, 1.05, grid_density)
        CRRA_list = np.linspace(2, 8, grid_density)
        CRRA_mesh, DiscFacAdj_mesh = pylab.meshgrid(CRRA_list, DiscFacAdj_list)
        smm_obj_levels = np.empty([grid_density, grid_density])
        for j in range(grid_density):
            DiscFacAdj = DiscFacAdj_list[j]
            for k in range(grid_density):
                CRRA = CRRA_list[k]
                smm_obj_levels[j, k] = smmObjectiveFxn(DiscFacAdj, CRRA)
        smm_contour = pylab.contourf(CRRA_mesh, DiscFacAdj_mesh,
                                     smm_obj_levels, level_count)
        pylab.colorbar(smm_contour)
        pylab.plot(model_estimate[1], model_estimate[0], '*r', ms=15)
        pylab.xlabel(r'coefficient of relative risk aversion $\rho$',
                     fontsize=14)
        pylab.ylabel(r'discount factor adjustment $\beth$', fontsize=14)
        pylab.savefig('SMMcontour.pdf')
        pylab.savefig('SMMcontour.png')
        pylab.show()
    # Calculate average within each MPC set
    simulated_MPC_means = np.zeros((4, 4))
    for k in range(4):
        for q in range(4):
            MPC_array = np.concatenate(MPC_set_list[k][q])
            simulated_MPC_means[k, q] = np.mean(MPC_array)

    # Calculate Euclidean distance between simulated MPC averages and Table 9 targets
    diff = simulated_MPC_means - MPC_target
    if drop_corner:
        diff[0, 0] = 0.0
    distance = np.sqrt(np.sum((diff)**2))
    if verbose:
        print(simulated_MPC_means)
    else:
        print(center, spread, distance)
    return distance


# %% {"code_folding": [0]}
# Conduct the estimation

guess = [0.92, 0.03]
f_temp = lambda x: FagerengObjFunc(x[0], x[1])
opt_params = minimizeNelderMead(f_temp, guess, verbose=True)
print('Finished estimating for scaling factor of ' + str(AdjFactor) +
      ' and "splurge amount" of $' + str(1000 * Splurge))
print('Optimal (beta,nabla) is ' + str(opt_params) + ', simulated MPCs are:')
dist = FagerengObjFunc(opt_params[0], opt_params[1], True)
print('Distance from Fagereng et al Table 9 is ' + str(dist))
Beispiel #4
0
def main(estimate_model=local_estimate_model,
         compute_standard_errors=local_compute_standard_errors,
         make_contour_plot=local_make_contour_plot):
    """
    Run the main estimation procedure for SolvingMicroDSOP.
    
    Parameters
    ----------
    estimate_model : bool
        Whether to estimate the model using Nelder-Mead. When True, this is a low-time, low-memory operation.
    
    compute_standard_errors : bool
        Whether to compute standard errors on the estiamtion of the model.
    
    make_contour_plot : bool
        Whether to make the contour plot associate with the estiamte. 
    
    Returns
    -------
    None
    """

    # Estimate the model using Nelder-Mead
    if estimate_model:
        initial_guess = [Params.DiscFacAdj_start, Params.CRRA_start]
        print(
            '--------------------------------------------------------------------------------'
        )
        print(
            'Now estimating the model using Nelder-Mead from an initial guess of '
            + str(initial_guess) + '...')
        print(
            '--------------------------------------------------------------------------------'
        )
        t_start_estimate = time()
        model_estimate = minimizeNelderMead(smmObjectiveFxnReduced,
                                            initial_guess,
                                            verbose=True)
        t_end_estimate = time()
        time_to_estimate = t_end_estimate - t_start_estimate
        print('Time to execute all:', round(time_to_estimate / 60., 2), 'min,',
              time_to_estimate, 'sec')
        print('Estimated values: DiscFacAdj=' + str(model_estimate[0]) +
              ', CRRA=' + str(model_estimate[1]))

        # Create the simple estimate table
        estimate_results_file = os.path.join(tables_dir,
                                             'estimate_results.csv')
        with open(estimate_results_file, 'wt') as f:
            writer = csv.writer(f)
            writer.writerow(['DiscFacAdj', 'CRRA'])
            writer.writerow([model_estimate[0], model_estimate[1]])

    if compute_standard_errors and not estimate_model:
        print(
            "To run the bootstrap you must first estimate the model by setting estimate_model = True."
        )

    # Compute standard errors by bootstrap
    if compute_standard_errors and estimate_model:

        # Estimate the model:
        print(
            '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        )
        print("Computing standard errors using", Params.bootstrap_size,
              "bootstrap replications.")
        print(
            '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        )
        try:
            t_bootstrap_guess = time_to_estimate * Params.bootstrap_size
            print("This will take approximately",
                  round(t_bootstrap_guess / 60., 2), "min, ",
                  t_bootstrap_guess, "sec")
        except:
            pass
        t_start_bootstrap = time()
        std_errors = calculateStandardErrorsByBootstrap(
            model_estimate,
            N=Params.bootstrap_size,
            seed=Params.seed,
            verbose=True)
        t_end_bootstrap = time()
        time_to_bootstrap = t_end_bootstrap - t_start_bootstrap
        print('Time to execute all:', round(time_to_bootstrap / 60., 2),
              'min,', time_to_bootstrap, 'sec')
        print('Standard errors: DiscFacAdj--> ' + str(std_errors[0]) +
              ', CRRA--> ' + str(std_errors[1]))

        # Create the simple bootstrap table
        bootstrap_results_file = os.path.join(tables_dir,
                                              'bootstrap_results.csv')
        with open(bootstrap_results_file, 'wt') as f:
            writer = csv.writer(f)
            writer.writerow([
                'DiscFacAdj', 'DiscFacAdj_standard_error', 'CRRA',
                'CRRA_standard_error'
            ])
            writer.writerow([
                model_estimate[0], std_errors[0], model_estimate[1],
                std_errors[1]
            ])

    # Make a contour plot of the objective function
    if make_contour_plot:
        print(
            '````````````````````````````````````````````````````````````````````````````````'
        )
        print("Creating the contour plot.")
        print(
            '````````````````````````````````````````````````````````````````````````````````'
        )
        t_start_contour = time()
        grid_density = 20  # Number of parameter values in each dimension
        level_count = 100  # Number of contour levels to plot
        DiscFacAdj_list = np.linspace(0.85, 1.05, grid_density)
        CRRA_list = np.linspace(2, 8, grid_density)
        CRRA_mesh, DiscFacAdj_mesh = pylab.meshgrid(CRRA_list, DiscFacAdj_list)
        smm_obj_levels = np.empty([grid_density, grid_density])
        for j in range(grid_density):
            DiscFacAdj = DiscFacAdj_list[j]
            for k in range(grid_density):
                CRRA = CRRA_list[k]
                smm_obj_levels[j, k] = smmObjectiveFxn(DiscFacAdj, CRRA)
        smm_contour = pylab.contourf(CRRA_mesh, DiscFacAdj_mesh,
                                     smm_obj_levels, level_count)
        t_end_contour = time()
        time_to_contour = t_end_contour - t_start_contour
        print('Time to execute all:', round(time_to_contour / 60., 2), 'min,',
              time_to_contour, 'sec')
        pylab.colorbar(smm_contour)
        pylab.plot(model_estimate[1], model_estimate[0], '*r', ms=15)
        pylab.xlabel(r'coefficient of relative risk aversion $\rho$',
                     fontsize=14)
        pylab.ylabel(r'discount factor adjustment $\beth$', fontsize=14)
        pylab.savefig(os.path.join(figures_dir, 'SMMcontour.pdf'))
        pylab.savefig(os.path.join(figures_dir, 'SMMcontour.png'))
        pylab.show()
Beispiel #5
0
def calculateStandardErrorsByBootstrap(initial_estimate,
                                       N,
                                       seed=0,
                                       verbose=False):
    '''
    Calculates standard errors by repeatedly re-estimating the model with datasets
    resampled from the actual data.

    Parameters
    ----------
    initial_estimate : [float,float]
        The estimated [DiscFacAdj,CRRA], for use as an initial guess for each
        re-estimation in the bootstrap procedure.
    N : int
        Number of times to resample data and re-estimate the model.
    seed : int
        Seed for the random number generator.
    verbose : boolean
        Indicator for whether extra output should be printed for the user.

    Returns
    -------
    standard_errors : [float,float]
        Standard errors calculated by bootstrap: [DiscFacAdj_std_error, CRRA_std_error].
    '''
    t_0 = time()

    # Generate a list of seeds for generating bootstrap samples
    RNG = np.random.RandomState(seed)
    seed_list = RNG.randint(2**31 - 1, size=N)

    # Estimate the model N times, recording each set of estimated parameters
    estimate_list = []
    for n in range(N):
        t_start = time()

        # Bootstrap a new dataset by resampling from the original data
        bootstrap_data = (bootstrapSampleFromData(Data.scf_data_array,
                                                  seed=seed_list[n])).T
        w_to_y_data_bootstrap = bootstrap_data[0, ]
        empirical_groups_bootstrap = bootstrap_data[1, ]
        empirical_weights_bootstrap = bootstrap_data[2, ]

        # Make a temporary function for use in this estimation run
        smmObjectiveFxnBootstrap = lambda parameters_to_estimate: smmObjectiveFxn(
            DiscFacAdj=parameters_to_estimate[0],
            CRRA=parameters_to_estimate[1],
            empirical_data=w_to_y_data_bootstrap,
            empirical_weights=empirical_weights_bootstrap,
            empirical_groups=empirical_groups_bootstrap)

        # Estimate the model with the bootstrap data and add to list of estimates
        this_estimate = minimizeNelderMead(smmObjectiveFxnBootstrap,
                                           initial_estimate)
        estimate_list.append(this_estimate)
        t_now = time()

        # Report progress of the bootstrap
        if verbose:
            print('Finished bootstrap estimation #' + str(n + 1) + ' of ' +
                  str(N) + ' in ' + str(t_now - t_start) + ' seconds (' +
                  str(t_now - t_0) + ' cumulative)')

    # Calculate the standard errors for each parameter
    estimate_array = (np.array(estimate_list)).T
    DiscFacAdj_std_error = np.std(estimate_array[0])
    CRRA_std_error = np.std(estimate_array[1])

    return [DiscFacAdj_std_error, CRRA_std_error]
Beispiel #6
0
            distance = np.sqrt(np.dot(moments_diff,moments_diff))
            
            print('Tried center=' + str(center) + ', spread=' + str(spread) + ', got distance=' + str(distance))
            print(moments_sim)
            return distance
        
        
        def objectiveFuncWrapper(params):
            return objectiveFuncWealth(params[0],params[1])
        
        arbitrary_param_guess = [0.95,0.045]
        estimate_liquid_with_unemp_benefits = [0.93286322, 0.06410639]
        estimate_liquid_without_unemp_benefits = [0.79100088, 0.22021331]
        estimate_networth_with_unemp_benefits = [0.97150587, 0.02211607]
        estimate_netwroth_without_unemp_benefits = [0.94717781, 0.04969883]
        estimated_params = minimizeNelderMead(objectiveFuncWrapper,arbitrary_param_guess)

        
    if estimate_by_MPC:
        # Define parameters for the beta-dist estimation
        TypeCount = 11
        cutoffs = [[0.,0.2],[0.2,0.4],[0.4,0.6],[0.6,0.8],[0.8,1.0]]
        moments_data = np.array([0.833741,0.752517,0.551613,0.437491,0.232213])
        # These target moments come from Crawley
        
        # Make the agent types
        BaseAgent = IndShockConsumerType(**temp_dict)
        Agents = []
        for j in range(TypeCount):
            Agents.append(deepcopy(BaseAgent))