# Consumption problem

Imports and set magics:


```python
import numpy as np
from scipy import stats as st
from scipy import optimize
import sympy as sm
import matplotlib.pyplot as plt
import math as m
import time           
import seaborn as sns 

# autoreload modules when code is run
%load_ext autoreload
%autoreload 2

# local modules
import modelproject
```

    The autoreload extension is already loaded. To reload it, use:
      %reload_ext autoreload


# Model description

In this analysis, we wish to find the optimal consumption of xxx for a consumer, here defined as the entire household. The initial amount 10 that needs to be split over a period of 7 days. 

<b>Theory<b>

We consider an Euler Equation where the consumer preferences in each period, t, follows the condition: 
* $u(c_t)$ = $ln(c_t)$

The consumption in future periods is discounted with factor $β<1$
indicating the time-preference of the consumer.

The present value of the consumption path set in period 0 is given by:
* $V(c_0, c_1,..., c_T)$ = $\sum_{t=0}^T$ $\beta^t U(c_t)$

The consumer wishes to optimize his consumption for every period, $t=0, ..., T$ but for period $t+1$ the amount left to consume is smaller by the amount consumed the period before, given by

* $k_{t+1}$ = $k_t - c_t$

Therefore the following restriction must hold
* $k_t \geq 0$


# Analytical solution of the problem

The analytical solution that we want to derive using **sympy** is found by first inserting the constraing into the consumption path as follows

$\beta^t U(k_{t-1}-k_t)$ + $\beta^{t+1} U(k_t-k_{t+1})$

We then derive the the objective function s.t. $k_t$ to find the Euler equation
$U'(c_{t-1})= \beta U'(c_t)$ 

This can be interpreted as stating that if the consumer wishes to shift in consumption between two periods, he will not gain from such a shift as a reduction in consumption in period $t$ equals a decrease in $U_t$ by the amount $U'_t$. The amount that the consumer then saves will be shifted to the next period, $t_{+1}$, increasing the total utility by a discounted amount, $U'_{t+1}$. This amount equals $\beta \bullet U'_{t1}$. 

We know that in optimum, $k_{t+1}=0$. 

By inserting the utility function in the Euler equation, we then find 

$c_{t+1}= \beta c_t$

Combining this and the budget constraint we find the solution of the problem given by

$c_0 = ((1-\beta)/(1-\beta)^{T+1}) k_0 $

First we define all **symbols**:


```python
t = 7
b = 0.7
k = np.zeros(t+1,float)
c = np.zeros(t+1,float)
u = np.zeros(t+1,float)
k[0] = 10  # k0
c[0] = (1.0-b)/(1.0-b**(t+1)) * k[0]  # c0
u[0] = np.log(c[0])

for i in range(1,t+1):
    #print "i=" + str(i)
    c[i] = beta * c[i-1]
    k[i] = k[i-1] - c[i-1]

    # Period utility with discounting
    u[i] = beta**(i-1)*np.log(c[i])

np.sum(u)  # total utility

print("c = " + str(c))
print("k = " + str(k))
```

    c = [3.18352381 2.22846667 1.55992667 1.09194867 0.76436407 0.53505485
     0.37453839 0.26217688]
    k = [10.          6.81647619  4.58800952  3.02808285  1.93613418  1.17177012
      0.63671527  0.26217688]


Next we **plot** the functions


```python
fig, ax = plt.subplots()
plt.subplots_adjust(wspace=0.5, hspace=0.8)
ax.plot(c, color='coral', linewidth=3)
ax.set_ylabel('$c^*_t$')
ax.set_xlabel('Period (t)')
ax.set_title('Optimal $c^*_t$')
plt.show()

fig, ax = plt.subplots()
plt.subplots_adjust(wspace=0.5, hspace=0.8)
ax.plot(k, color='green', linewidth=3)
ax.set_ylabel('$k_t$')
ax.set_xlabel('Period (t)')
ax.set_title('Amount, $k_t$')
plt.show()
#, colour="green", size=0.4
```

###WRITE SOMETHING ABOUT FINDINGS

## Numerical solution

The general model is given by the utility function 

$\sum_{t=0}^T$ $\beta^t U(c_t)$ 

with one constraint
    $c_0,...c_t = k_0$

Stating that it is not possible to consume more of the good than the 10 acquired goods. 


We now define the **utility function**:


```python
def utility(c):
    t = len(c)
    u= np.zeros(t,float)
    for i in range(t):
        b = 0.7
        #Calculating the utility of the entire period, disregarding the discount factor
        u[i] = (b**i) * np.log(c[i])

#to maximize the result, we take the negative result
    return (-np.sum(u))

#We then define the constraint above as
def constraint(c):
    k[0] = 10
    x_1 = np.sum(c) - k[0]
    return np.array([x_1])
```

**Solve** by calling the optimizer:


```python
time = 10

#Now we initialize a guess for optimal c
c_guess = 0.3*np.ones(time,float)

#Using the optimizing function
c_op = optimize.fmin_slsqp(utility, c_guess, f_eqcons = constraint)

#Printing the solution
print(c_op)

```

    Optimization terminated successfully.    (Exit mode 0)
                Current function value: -1.2914761304307483
                Iterations: 13
                Function evaluations: 157
                Gradient evaluations: 13
    [3.08814661 2.15928281 1.51399323 1.05921944 0.74034874 0.51902058
     0.36328604 0.25423064 0.17795569 0.12451622]


Plotting the optimal consumtion of the period


```python
palette = sns.color_palette("mako_r", 2)
ax = sns.lineplot(data=c, hue="coherence", style="choice", palette=palette)
ax = sns.lineplot(data=c_op, hue="coherence", style="choice", palette=palette)
ax.set_title("Optimal consumption")
ax.set_xlabel("Period (t)")
ax.set_ylabel("$c^*_t$")
ax.legend(['C', 'C_op'], loc='mid', shadow=False)
plt.show()


```

# Results from the analysis


```python
#Printing the results from calculations above

print('Analytical result')
print('c* = {}'.format(c))


print('Numerical result')
print('c* = {}'.format(c_op))

```

    Analytical result
    c* = [3.18352381 2.22846667 1.55992667 1.09194867 0.76436407 0.53505485
     0.37453839 0.26217688]
    Numerical result
    c* = [3.08814661 2.15928281 1.51399323 1.05921944 0.74034874 0.51902058
     0.36328604 0.25423064 0.17795569 0.12451622]


# Conclusion

From the analysis above we see, that the analytical solution and the numerical solution are ...

4687a9fc38357ef96da357089b9156ee06b14e69
ipynb
Jupyter Notebook
modelproject/modelproject.ipynb
zenghijacob/projects-2020-zjr-hrv
655cdf814beb02f00f51d3a2e0a01955fb4f71cd
MIT
modelproject/modelproject.ipynb
zenghijacob/projects-2020-zjr-hrv
655cdf814beb02f00f51d3a2e0a01955fb4f71cd
MIT
modelproject/modelproject.ipynb
zenghijacob/projects-2020-zjr-hrv
655cdf814beb02f00f51d3a2e0a01955fb4f71cd
MIT
Qwen/Qwen-72B
1. YES
2. YES