def firstbest(fp,cp):
    #ststkfp.AA=alpha/((1/beta-1)+delta)
    #fp.AA= 1.0/(ststkfp.AA**alpha *  L**(1.0-alpha)  )
    ##Get average productivity
    mc = MarkovChain(cp.Pi)
    stationary_distributions = mc.stationary_distributions[0]
    E = np.dot(stationary_distributions, cp.z_vals)
    def fbfoc(l):
        #l = np.min([np.max([x,0.001]),.999])
        L = E*(1-l)
        K = L*(((1-cp.beta +fp.delta*cp.beta)/(fp.AA*fp.alpha*cp.beta))**(1/(fp.alpha-1)))
        Y = fp.AA*(K**fp.alpha)*(L**(1-fp.alpha))
        Fl = -E*fp.AA*(1-fp.alpha)*(K**fp.alpha)*(L**(-fp.alpha))
        diff = cp.du(Y - fp.delta*K)*Fl + cp.dul(l)
        #print(cp.du(Y - fp.delta*K)*Fl )
        return diff
    
    l = fsolve(fbfoc, .5)[0]
    Labour_Supply = E*(1-l)
    L = E*(1-l)
    Hours = 1-l
    K = L*(((1-cp.beta +fp.delta*cp.beta)/(fp.AA*fp.alpha*cp.beta))**(1/(fp.alpha-1)))
    Y = fp.AA*np.power(K,fp.alpha)*np.power(L,1-fp.alpha)
    #r = fp.AA*fp.alpha*np.power(K,fp.alpha-1)*np.power(L,1-fp.alpha)- fp.delta
    r,w,fkk = K_to_rw(K, L,fp)
    return r, K, Hours,Labour_Supply, Y, w 
コード例 #2
0
ファイル: lq_markov.py プロジェクト: cnxtech/TaxSmoothing
    def compute_sequence(self, x0, ts_length=None):
        """ 
        This Function simulates x,u,w.
        It is based on the compute_sequence function from the LQ class, but is amended to recognise
        the fact that the A,B,C matrices can depend on the state of the world
        """
        x0 = np.asarray(x0)
        x0 = x0.reshape(self.nx, 1)

        T = ts_length if ts_length else 100

        chain = MarkovChain(self.Pi)
        state = chain.simulate_indices(ts_length=T + 1)

        x_path = np.empty((self.nx, T + 1))
        u_path = np.empty((self.nu, T))
        shocks = np.random.randn(self.nw, T + 1)
        w_path = np.empty((self.nx, T + 1))
        for i in range(T + 1):
            w_path[:, i] = self.C[state[i] + 1].dot(shocks[:, i])

        x_path[:, 0] = x0.flatten()
        u_path[:, 0] = -dot(self.F[state[0] + 1], x0).flatten()
        for t in range(1, T):
            Ax, Bu = dot(self.A[state[t] + 1],
                         x_path[:, t - 1]), dot(self.B[state[t] + 1],
                                                u_path[:, t - 1])
            x_path[:, t] = Ax + Bu + w_path[:, t]
            u_path[:, t] = -dot(self.F[state[t] + 1], x_path[:, t])
        Ax, Bu = dot(self.A[state[T] + 1],
                     x_path[:, T - 1]), dot(self.B[state[T] + 1],
                                            u_path[:, T - 1])
        x_path[:, T] = Ax + Bu + w_path[:, T]

        return x_path, u_path, w_path, state
コード例 #3
0
    def __init__(self, model, μgrid):

        self.β, self.π, self.G = model.β, model.π, model.G
        self.mc, self.S = MarkovChain(self.π), len(model.π)  # Number of states
        self.Θ, self.model, self.μgrid = model.Θ, model, μgrid

        # Find the first best allocation
        self.solve_time1_bellman()
        self.T.time_0 = True  # Bellman equation now solves time 0 problem
コード例 #4
0
    def __init__(self, model):

        # Initialize from model object attributes
        self.β, self.π, self.G = model.β, model.π, model.G
        self.mc, self.Θ = MarkovChain(self.π), model.Θ
        self.S = len(model.π)  # Number of states
        self.model = model

        # Find the first best allocation
        self.find_first_best()
    def __init__(self, model):

        # Initialize from model object attributes
        self.beta, self.pi, self.G = model.beta, model.pi, model.G
        self.mc, self.Theta = MarkovChain(self.pi), model.Theta
        self.S = len(model.pi)  # Number of states
        self.model = model

        # Find the first best allocation
        self.find_first_best()
コード例 #6
0
 def __init__(self, model):
     '''
     Initializes the class from the calibration model
     '''
     self.β, self.π, self.G = model.β, model.π, model.G
     self.mc = MarkovChain(self.π)
     self.S = len(model.π)  # number of states
     self.Θ = model.Θ
     self.model = model
     # now find the first best allocation
     self.find_first_best()
コード例 #7
0
 def __init__(self, model):
     '''
     Initializes the class from the calibration model
     '''
     self.beta, self.pi, self.G = model.beta, model.pi, model.G
     self.mc = MarkovChain(self.pi)
     self.S = len(model.pi)  # number of states
     self.Theta = model.Theta
     self.model = model
     # now find the first best allocation
     self.find_first_best()
コード例 #8
0
 def __init__(self,Para):
     '''
     Initializes the class from the calibration Para
     '''
     self.beta = Para.beta
     self.Pi = Para.Pi
     self.mc = MarkovChain(self.Pi)
     self.G = Para.G
     self.S = len(Para.Pi) # number of states
     self.Theta = Para.Theta
     self.Para = Para
     #now find the first best allocation
     self.find_first_best()
コード例 #9
0
 def __init__(self,Para,mugrid):
     '''
     Initializes the class from the calibration Para
     '''
     self.beta = Para.beta
     self.Pi = Para.Pi
     self.mc = MarkovChain(self.Pi)
     self.G = Para.G
     self.S = len(Para.Pi) # number of states
     self.Theta = Para.Theta
     self.Para = Para
     self.mugrid = mugrid
     
     #now find the first best allocation
     self.solve_time1_bellman()
     self.T.time_0 = True #Bellman equation now solves time 0 problem
コード例 #10
0
from quantecon import MarkovChain

lm = LakeModel(d=0, b=0)
T = 5000  # Simulation length

α, λ = lm.α, lm.λ

P = [[1 - λ,    λ],
     [α,    1 - α]]

mc = MarkovChain(P)

xbar = lm.rate_steady_state()

fig, axes = plt.subplots(2, 1, figsize=(10, 8))
s_path = mc.simulate(T, init=1)
s_bar_e = s_path.cumsum() / range(1, T+1)
s_bar_u = 1 - s_bar_e

axes[0].plot(s_bar_u, '-b', lw=2, alpha=0.5)
axes[0].hlines(xbar[0], 0, T, 'r', '--')
axes[0].set_title('Percent of time unemployed')

axes[1].plot(s_bar_e, '-b', lw=2, alpha=0.5)
axes[1].hlines(xbar[1], 0, T, 'r', '--')
axes[1].set_title('Percent of time employed')

plt.tight_layout()
plt.show()
    model_in = pickle.load(model)

    name = model_in["filename"]

    cp.gamma_c = model_in["gamma_c"] 
    cp.gamma_l = model_in["gamma_l"]
    cp.A_L     = model_in["A_L"]
    cp.Pi      = np.asarray(model_in["Pi"])
    cp.z_vals  = np.asarray(model_in["z_vals"])

    model.close()

    #====Normalize mean of Labour distributuons===#

    mc = MarkovChain(cp.Pi)
    stationary_distributions = mc.stationary_distributions
    mean = np.dot(stationary_distributions, cp.z_vals)
    cp.z_vals = cp.z_vals/ mean   ## Standardise mean of avaible labour supply to 1
    z_seq = mc.simulate(T)


    #===Create Dict for Saving Results===#

    Results = {}

    Results["Name of Model"] = model_in["name"]

    #====Calcuate First Best===#

    fb_r, fb_K, fb_H, fb_L, fb_Y, fb_w  = firstbest(fp,cp)
コード例 #12
0
ファイル: main.py プロジェクト: egbuck/ormm
def analyze_dtmc(P,
                 states=None,
                 sim_kwargs=None,
                 trans_kwargs=None,
                 cost_kwargs=None):
    """
    Perform Markov Analysis of discrete time discrete state markov chain
    (DTMC) process.

    Parameters
    ----------
    P : array-like
        The transition matrix.  Must be of shape n x n.
    states : array-like
        Array_like of length n containing the values associated with the
        states, which must be homogeneous in type. If None, the values
        default to integers 0 through n-1.
    sim_kwargs : dict
        Dictionary of key word arguments to be passed to the simulation
        of the markov process.  If None, then no simulation will be performed.
        These include ts_length (length of each
        simulation) and init (Initial state values).
    trans_kwargs : dict
        Dictionary of options for the transient probability analysis (tsa).
        If None is passed instead of dict, no tsa will be done.
        ts_length is the number of time periods to analyze, while init is
        the initial state probability vector.
    cost_kwargs : dict
        Dictionary of cost parameters for cost analysis.  If None, then
        no cost analysis will be performed.  These include state (vector of
        costs of being in each state), transition (matrix of costs of
        transitioning from one state to another), and num (number of
        these processes - total cost multiplied by this, default 1).

    Returns
    -------
    analysis : dict
        Dictionary with results of markov analysis

    Raises
    ------
    ValueError
        If sim_kwargs, trans_kwargs, or cost_kwargs is given, but their
        required arguments are not passed.  These are described in the
        Notes section.

    Notes
    -----
    The required arguments if the kwargs are passed are:

    * sim_kwargs: `ts_length` is required, the length of the sim.

    * trans_kwargs: `ts_length` is required, the number of periods
      to analyze

    * cost_kwargs: `state` and `transition` are required, which are the
      costs of being in any state and the costs of transitioning from one
      state to another.
    """
    analysis = {}
    markov = MarkovChain(P, states)
    analysis["cdfs"] = markov.cdfs
    steady_state = markov.stationary_distributions[0]
    analysis["steady_state"] = {"output": steady_state}
    if sim_kwargs:
        if "ts_length" not in sim_kwargs:
            raise ValueError(("Required argument `ts_length` in sim_kwargs! "
                              "None was given."))
        if "init" not in sim_kwargs:
            sim_kwargs["init"] = None
        analysis["sim"] = {
            "kwargs": sim_kwargs,
            "output": markov.simulate(**sim_kwargs)
        }
    if trans_kwargs:
        if "ts_length" not in trans_kwargs:
            raise ValueError(("Required argument `ts_length` in trans_kwargs! "
                              "None was given."))
        if "init" not in trans_kwargs:
            trans_kwargs["init"] = None
        trans_probs = _transient_probs(P, states, **trans_kwargs)
        analysis["transient"] = {"kwargs": trans_kwargs, "output": trans_probs}
    if cost_kwargs:
        if "state" not in cost_kwargs:
            raise ValueError(("Required argument `state` in trans_kwargs! "
                              "None was given."))
        if "transition" not in cost_kwargs:
            raise ValueError(("Required argument `transition` in trans_kwargs!"
                              " None was given."))
        if "num" not in cost_kwargs:
            cost_kwargs["num"] = 1
        # Cost of steady state
        cost_vector, cost_total = _cost_analysis(P, steady_state,
                                                 **cost_kwargs)
        # Cost of transient analysis
        analysis["steady_state"]["cost"] = \
            {"kwargs": cost_kwargs,
             "total": cost_total, "vector": cost_vector}
        if trans_kwargs:
            cost_vector, cost_total = _cost_analysis(P, trans_probs,
                                                     **cost_kwargs)
            analysis["transient"]["cost"] = {
                "kwargs": cost_kwargs,
                "total": cost_total,
                "vector": cost_vector
            }
    return analysis
コード例 #13
0
from quantecon import MarkovChain
import numpy as np

failureProbabilities = [0.2, 0.4, 0.3, 0.1]

transitionMatrix = np.zeros(
    (len(failureProbabilities), len(failureProbabilities)))
currentDenominator = 1
for i in range(len(transitionMatrix)):
    transitionProbability = failureProbabilities[i] / currentDenominator
    transitionMatrix[i, 0] = transitionProbability
    if i < len(transitionMatrix) - 1:
        transitionMatrix[i, i + 1] = 1 - transitionProbability
    currentDenominator *= 1 - transitionProbability

print(transitionMatrix)

mc = MarkovChain(transitionMatrix)
age = np.array(
    np.linspace(0,
                len(failureProbabilities),
                num=len(failureProbabilities),
                dtype=np.dtype(np.int16)))
stationaryVector = np.array(mc.stationary_distributions[0, :])
print(stationaryVector)
print(sum(age * stationaryVector))