In [1]:
# packages
using DataFrames, CSV, Statistics, LinearAlgebra, Plots, StatsPlots, GLM, Random, Optim

cd("C:/Users/Eric/Documents/GitHub/Econ-543/PS 2/data")  # adjust path as needed
consumer_census = DataFrame(CSV.File("consumer_census.csv"))
product_data = DataFrame(CSV.File("product_data_ps2.csv"))
Out[1]:
2500×9 DataFrame
2475 rows omitted
Rowproduct_IDpricesugarcaffeinecorn_syrup_pricecaffeine_extract_pricequantitytmarket_share
Int64Float64Float64Float64Float64Float64Int64Int64Float64
112.021331.580866.074460.1990220.26489922310.0223
221.980253.033155.26060.1990220.2648993910.0039
331.655561.718884.685730.1990220.2648998310.0083
441.566472.637864.250370.1990220.2648991610.0016
551.517631.476214.13780.1990220.26489914110.0141
661.935131.017067.048040.1990220.2648999210.0092
772.015921.838515.939920.1990220.26489915110.0151
882.394192.467937.008690.1990220.26489932210.0322
991.751082.569614.578630.1990220.2648994710.0047
10101.86272.835814.649170.1990220.2648997110.0071
11111.312291.105883.972620.1990220.2648996910.0069
12121.79453.015624.749480.1990220.2648992110.0021
13131.750791.648435.471860.1990220.2648994410.0044
⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮
2489392.640747.429924.672660.2105640.255062272500.0272
2490402.358623.322816.439180.2105640.255062101500.0101
2491413.003016.360236.138070.2105640.2550621073500.1073
2492422.58265.731715.318550.2105640.255062166500.0166
2493432.368555.795714.552790.2105640.255062112500.0112
2494441.969813.883615.008910.2105640.25506214500.0014
2495452.797465.644656.535250.2105640.255062162500.0162
2496462.368633.699035.598460.2105640.255062252500.0252
2497471.719464.031763.961570.2105640.25506212500.0012
2498482.529197.770443.606250.2105640.2550621158500.1158
2499491.674553.751783.642180.2105640.25506230500.003
2500502.017273.825394.590950.2105640.25506263500.0063

Introduction¶

This homework assignment will give you practice working with the basics of the random coefficients multinomial logit demand model (Berry 1994). Compared to Problem set 1, we will now introduce three new sources of consumer heterogeneity:

  1. Consumer demographic characteristics (income)
  2. Unobserved preference for sugar
  3. Unobserved preference for caffeine

The file product_data_ps2.csv contains information on 50 different soft drinks, for 50 different markets. This dataset contains the following variables: product_ID (the product ID), type (a variable indicating if the product is a diet or a regular soda), price (the product's price during period $t$, in USD), quantity (the number of cans sold in market $t$), sugar (the grams of sugar contained in product $j$ at time $t$), caffeine (the milligrams of caffeine contained in product $j$ at time $t$), caffeine_extract_price (the price of caffeine at time $t$), corn_syrup_price (the price of high fructose corn syrup at time $t$), and $t$ (the observation's time period). Throughout this problem set, assume that the market size is $M_t = \bar{M} = 10,000$ for all markets.

Let $\mathcal{J}_t = \{1,...,J_t\}$ denote the set of all products available in market $t$. As usual, let $j = 0$ denote the outside good (not consuming any product).

Consumer $i$'s indirect utility from consuming soda $j$ in market $t$ is given by the following expression:

$$u_{ijt} = \gamma + \alpha_i p_{jt} + \beta_1 sug_{jt} + \beta_2 caf_{jt} + \xi_{jt} + \varepsilon_{ijt}$$

with $$\alpha_i = p_{jt} (\hat{\alpha} + \alpha^y y_{it}),$$ $$\beta_{1it} = \bar{\beta}_1 + \nu_{1it} \sigma_1, \quad \nu_{1it} \sim N(0,1)$$ $$\beta_{2it} = \bar{\beta}_2 + \nu_{2it} \sigma_2, \quad \nu_{2it} \sim N(0,1)$$

Problem 1 (a)¶

The file consumer_census.csv contains micro-level data on households' income for each market $t$ in our sample. Let $\bar{y}_t$ denote the average income in market $t$, let $\sigma_{yt}$ denote the variance of $y_{it}$ in market $t$, and let $\bar{p}_t = \sum_j p_{jt} s_{jt}$ denote the average price paid in market $t$.

  1. Compute $\bar{y}_t$, $\sigma_{yt}$, and $\bar{p}_t$ for each market.
  2. Compute $\text{cor}(\bar{y}_t, \bar{p}_t)$. Do consumers in wealthier markets buy more expensive products on average?
In [2]:
# Problem 1(a) solution
mean_income = combine(groupby(consumer_census, :t), 
    :income => mean => :mean_income)

var_income = combine(groupby(consumer_census, :t), 
    :income => var => :var_income)

product_data[!, :market_share] .= product_data.quantity ./ 10000

grouped_product = groupby(product_data, :t)
p_bar = combine(grouped_product) do sdf
    DataFrame(p_bar = mean(sdf.price .* sdf.market_share))
end

market_data = innerjoin(mean_income, p_bar, on = :t)

correlation = cor(market_data.mean_income, market_data.p_bar)
println(correlation)
0.15430274953743087

Problem 1(b)¶

Write a function that takes the observed distribution of income of each market, the number of consumers to be simulated ($S$), and a random seed (for replicability) as inputs, and uses pseudo-Monte Carlo draws to return a simulated sample of $S$ consumers for each market $t$. For each consumer $i$ and each market $t$, the output of this function must contain $y_{it}$, $\nu_{1it}$, and $\nu_{2it}$. Use this function to draw a sample of 500 consumers for each market $t$.

In [3]:
function simulate_consumers(consumer_census::DataFrame, S::Int, seed::Int)
    Random.seed!(seed)

    # Split the data by the 't' column
    grouped_census = groupby(consumer_census, :t)

    simulated_consumers = DataFrame()
    
    tt = 1
    for sub_df in grouped_census
        income_sample = rand(sub_df.income, S)
        
        simulated_consumers_current_t = DataFrame(
            consumer_ID = 1:S,
            income = income_sample,
            t = fill(tt, S),
            nu_1 = randn(S),
            nu_2 = randn(S)
        )
        
        append!(simulated_consumers, simulated_consumers_current_t)
        
        tt += 1
    end

    return simulated_consumers
end

sample = simulate_consumers(consumer_census, 500, 123)
Out[3]:
25000×5 DataFrame
24975 rows omitted
Rowconsumer_IDincometnu_1nu_2
Int64Float64Int64Float64Float64
115.687791-0.563549-0.264958
226.1919810.2273260.230161
335.8535810.01029160.249837
445.566371-0.760516-0.283196
555.6598211.397990.501889
666.106021-0.3435640.385318
776.892511-1.54224-2.85127
886.505291-1.3-0.259393
995.558761-1.057671.12154
10106.196811-0.5491241.62369
11116.4475811.12477-0.372927
12125.6277111.232011.18332
13136.2640510.08756161.65032
⋮⋮⋮⋮⋮⋮
249894896.01369500.08968440.11497
249904905.62916502.30871-0.448778
249914916.04779500.991243-0.460348
249924925.3270450-1.5506-0.856875
249934935.8929150-0.18464-1.16149
249944945.62934500.8408270.8664
249954956.07691500.00597359-1.69253
249964967.33057500.8160411.5106
249974975.82752500.0781450.506398
249984986.89597500.334505-1.20558
249994996.3459250-0.13720.303473
250005006.0283950-0.392797-1.46894

Problem 1(c)¶

Given our distributional assumptions over $\varepsilon_{ijt}$, the probability that consumer $i$ in market $t$, with heterogeneity given by $y_{it}$, $\nu_{1it}$, and $\nu_{2it}$ purchases product $j$ is given by:

$s_{ijt}(\delta_t, \theta_2) = \text{Pr}(u_{ijt} \geq u_{ikt} \forall k \in \mathcal{J}_t) = \frac{\exp(\delta_{jt} + \mu_{ijt}(\theta_2))}{1 + \sum_k \exp(\delta_{kt} + \mu_{ikt}(\theta_2))}$

Note that when computing $s_{ijt}$, it is important to only consider the goods available in $is market ($\mathcal{J}_t$).

Let $\mathcal{S}$ denote the set of simulated consumers you obtained in Problem 1(b). Write a function that, given the parameters $\delta_t = \{\delta_{1t}, \ldots, \delta_{J_t,t}\}$ and $\theta_2 = \{\alpha, \sigma_1, \sigma_2\}$ computes the vector of individual choice probabilities $s_{ijt} = \text{Pr}(u_{ijt} \geq u_{ikt} \forall k \in \mathcal{J}_t)$ for all $i \in \mathcal{S}$. You will use this function for part (d).

In [4]:
function s_ijt(simulated_consumers::DataFrame, delta_table::DataFrame, product_data::DataFrame, nonlinear_param::Dict{Symbol, Float64})
    
    alpha = nonlinear_param[:alpha]
    sigma_1 = nonlinear_param[:sigma_1]
    sigma_2 = nonlinear_param[:sigma_2]
    
    product_variables = innerjoin(delta_table, product_data, on = [:product_ID, :t])
    
    grouped_simulated = groupby(simulated_consumers, :t)
    grouped_product = groupby(product_variables, :t)

    individual_shares = DataFrame()
    
    for tt in 1:length(grouped_product)
        
        data = sort(grouped_product[tt], :product_ID)
        n_j = nrow(data)
        
        consumer_census_t = sort(grouped_simulated[tt], :consumer_ID)
        
        income_data = transpose(repeat(consumer_census_t.income, 1, n_j))
        sugar_taste = transpose(repeat(consumer_census_t.nu_1, 1, n_j))
        caffeine_taste = transpose(repeat(consumer_census_t.nu_2, 1, n_j))
        
        mu_ijt = alpha .* data.price .* income_data .+ sigma_1 .* sugar_taste .* data.sugar .+ sigma_2 .* caffeine_taste .* data.caffeine
        utility = mu_ijt .+ data.delta
        
        # Calculate utility from outside option
        outside_option = zeros(size(utility, 2))     
       
         # Calculate inclusive values (log-sum-exp over rows)
        inclusive_values = log.(sum(exp.(vcat(utility, outside_option')), dims=1))
        
         current_shares = exp.(utility .- inclusive_values)
        
        current_shares_df = DataFrame(current_shares, :auto)
        rename!(current_shares_df, string.(consumer_census_t.consumer_ID))
        current_shares_df.product_ID = data.product_ID
        current_shares_df.t = fill(tt, nrow(current_shares_df))
        
        append!(individual_shares, current_shares_df)
        
    end
    
    return individual_shares
    
end
Out[4]:
s_ijt (generic function with 1 method)

Problem 1(d)¶

Suppose the linear parameters are $\hat{\alpha} = -1$, $\bar{\beta}_1 = 0.5$, $\bar{\beta}_2 = 0.5$, and $\gamma = -1.5$. Compute $\delta_{jt}$ for each product and each market, assuming $\xi_{jt} = 0 \forall j, t$. Call the vector of $\delta$'s you get $\delta^0$. Let $\theta_2^0 = (\alpha^y, \sigma_1^y, \sigma_2^y) = (0, 0, 0)$.

Compute the conditional shares $s_{ijt}(\delta_t^0, \theta_2^0)$ for each consumer. Let $\theta_2^1 = (\alpha^y, \sigma_1^1, \sigma_2^1) = (0.05, 1, 1)$. Compute the conditional shares $s_{ijt}(\delta_t^0, \theta_2^1)$. Comment on how the conditional probabilities change if we use $\theta_2^1$ or $\theta_2^0$.

In [5]:
function get_delta(product_data::DataFrame, linear_parameters::Dict{Symbol, Float64}; xi::Bool=false, xi_hat::DataFrame=DataFrame())
    
    product_variables = copy(product_data)
    
    alpha_bar = linear_parameters[:alpha_bar]
    beta_1 = linear_parameters[:beta_1]
    beta_2 = linear_parameters[:beta_2]
    intercept = linear_parameters[:intercept]
    
    if xi
        product_variables = innerjoin(product_variables, xi_hat, on = [:product_ID, :t])
        product_variables.delta = intercept .+ alpha_bar .* product_variables.price .+ beta_1 .* product_variables.sugar .+ beta_2 .* product_variables.caffeine .+ product_variables.xi
    else
        product_variables.delta = intercept .+ alpha_bar .* product_variables.price .+ beta_1 .* product_variables.sugar .+ beta_2 .* product_variables.caffeine
    end
    
    delta_table = select(product_variables, :product_ID, :delta, :t)
    
    return delta_table
    
end
Out[5]:
get_delta (generic function with 1 method)
In [6]:
linear_parameters = Dict(
    :alpha_bar => -1.0,
    :beta_1 => 0.5,
    :beta_2 => 0.5,
    :intercept => -1.5
)

delta_table = get_delta(product_data, linear_parameters)

theta_2_prime = Dict(
    :alpha => 0.0,
    :sigma_1 => 0.0,
    :sigma_2 => 0.0
)

theta_2_double_prime = Dict(
    :alpha => 0.0,
    :sigma_1 => 1.0,
    :sigma_2 => 1.0
)

individual_shares_prime = s_ijt(sample, delta_table, product_data, theta_2_prime)

individual_shares_prime_prime = s_ijt(sample, delta_table, product_data, theta_2_double_prime)
Out[6]:
2500×502 DataFrame
402 columns and 2475 rows omitted
Row123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100⋯
Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64⋯
10.02094670.00698440.01295820.02178947.40465e-50.02753483.56659e-90.01933890.04357520.02848150.0001009530.0002535980.01162170.0001569980.01561120.009847820.0002375562.85719e-60.002411070.04037770.0009130440.0002795080.0008808720.003683820.03772943.58705e-55.02292e-50.002060060.005931580.001880980.01265450.01116950.001363730.01441610.0134610.005367220.02644360.02839920.01363635.46991e-70.02238770.0005729190.0265023.87828e-50.03464810.03967810.02884780.001217830.00012990.0001274290.0002072220.0096260.001288780.002567550.0009218982.03344e-50.007407140.02050365.51174e-50.00724920.001127140.007751130.01883320.002744890.002724720.002028180.0001799950.009014170.02420060.05150120.03496470.001270580.02178140.004133542.86526e-60.05014070.01823110.04828179.56796e-50.02376228.94103e-61.85517e-50.0001900290.02586120.01784650.0001822250.006164948.27957e-60.001146780.007040816.71712e-50.03805660.005185140.0007418950.0001592330.00961150.003363460.0007012990.01404490.00313568⋯
20.01643610.01155140.01538880.0130360.000537440.01751755.54373e-90.005183870.005397670.004906740.001004220.000830670.004939220.001319360.01459780.004543110.002067248.134e-60.00239970.005686850.001307830.001986220.0009660510.001530810.001973770.0006036470.0005626360.0005804990.010950.005480460.01740620.003885910.005546530.01660190.01732090.0121010.01842750.00331450.01788453.9493e-60.01045780.001622970.01126986.4653e-50.01153680.009252350.01546450.002669354.5028e-50.001430870.001603880.006126740.00471860.008000420.004274220.0004244410.01235230.01722760.0003644370.006474480.00535090.008702070.01781290.007263010.0028910.0004445940.001606260.01551560.01508070.005033330.008289920.004297620.01927880.0007681736.11529e-50.003907570.01837740.01039120.0010650.00109920.0001394270.0001984870.001226280.008167080.01796350.001587210.01174771.88694e-50.003858180.012626.99616e-60.01167840.005675330.003827540.001658470.0105740.009857570.003323350.01384050.0067502⋯
30.02159740.004038370.007075290.02242463.4504e-50.01186211.16608e-70.01787390.00611910.002136180.000152664.48308e-50.0009171590.0002119940.01928830.01275830.0006518583.17753e-50.0002113780.0224177.74705e-50.001459060.002468260.0001228730.01641030.0001277215.68726e-50.003270540.003804980.001219510.01402770.01298190.001782640.008644730.01045580.006022220.02158130.001611410.01282461.09813e-50.003872540.000131820.004984750.0002244870.007152760.0246210.02420070.0002821220.0003737030.0004813240.0002837080.001154920.001095730.003007340.001167080.0002103990.004732990.009652610.0004424220.001193780.002270710.01309660.01050040.002014760.0002885850.002997990.00104050.01130560.007659830.01440760.0240860.004196310.01467730.005034181.99834e-60.01703170.0117540.01621430.0002070360.0007276476.30015e-68.29419e-60.001138380.003153910.01081180.001063250.004584967.04705e-50.0006853880.01196470.0001526390.02510920.0009328720.001060390.000628170.003027770.006076950.0006966740.005389250.00151788⋯
40.02010440.006267940.008919130.0175570.0001395190.01018351.3615e-70.00843590.001977970.0008855030.000702830.0001156790.0006746320.0008824040.0198630.008343830.00265755.82962e-50.0002660060.007235420.0001232520.005026260.002677699.3877e-50.002856210.0007809180.0002874640.001542130.00629530.00269850.01860490.0071370.004677440.01062510.01357940.01094250.01888960.0005298180.01666543.52136e-50.00288490.0003050970.003479530.0003044770.004246790.01089130.01788550.0005540910.0001939950.002264760.001119530.001071830.002759540.006701020.003335880.001383510.00734030.009844210.0014180.001349260.006405910.01487170.01143170.004160740.0003739870.001209410.004119920.01717370.006612150.003839010.01070020.009252130.01514110.001849191.57004e-50.003881360.01321070.007073480.001002060.000137554.04848e-54.30764e-50.003656770.001869130.01218630.0041430.007671810.0001140030.001670750.01831023.72992e-50.01318680.001194140.003221120.002809710.003758360.0126830.002049270.006161260.00281802⋯
50.02213460.00260440.004758130.02434961.44323e-50.00807066.25144e-70.02183610.003307490.0007751080.0001101941.34395e-50.0002810160.0001496160.0209140.01652560.0006608938.51457e-55.68987e-50.02413511.89458e-50.002161570.003962762.41437e-50.01927930.0001285853.44059e-50.005240920.002529490.0007384780.01322050.01689130.001447620.006145590.008304930.005131740.02008920.0005500160.01120863.27296e-50.001750384.67886e-50.002402090.0004805230.003815220.02518450.02418980.0001062370.0007806790.0005455160.0002053060.0004033860.0007273750.002443290.0009059580.000352630.003209940.006476090.0008332420.0004570260.002234430.0160690.007499750.001329088.45502e-50.004887330.001547430.01082490.004457470.01174370.02592360.005750840.01173940.007688478.16564e-70.01613370.008931870.01225220.0001758170.0002200232.7703e-63.12145e-60.001850270.001293180.007956020.001597340.003269840.000172360.0003855860.01330490.0003658680.02498750.0003578860.0008568550.0007402310.001553940.006272110.0004743160.003139660.000842731⋯
60.02975060.01028510.02198280.03397377.34234e-50.06506527.09124e-100.04182990.3153880.252334.98261e-50.0005360920.07379818.68628e-50.01907550.01494679.10146e-57.93887e-70.01086980.1404040.003696448.31089e-50.0006761410.03630420.2077559.63398e-62.75264e-50.003339790.007986790.002156620.01431650.0197070.0009819090.02357880.01862030.005100470.0439710.3304250.01702668.23224e-80.09287450.001114980.1088471.79402e-50.1476110.1098980.05173210.002577590.0001456613.81344e-50.0001170930.04317710.00119330.00213880.0006451092.97246e-60.01034510.04215331.3536e-50.02471860.0006197920.007606670.03416460.003055890.01093210.00371234.70554e-50.008880890.06721950.2860030.09138010.0006119950.03675250.008819961.60746e-60.272870.03008870.1869783.79743e-50.5162465.5532e-61.64565e-55.44935e-50.1460660.03040264.78092e-50.007624842.83778e-60.001304130.005875050.000127680.09308750.01578150.0004710424.78339e-50.0220510.002301980.0005500730.03030220.00461448⋯
70.02007350.007677240.01343330.01989650.0001060960.02558643.76152e-90.01531810.030510.02124860.0001516550.0003176530.01017950.0002290630.01541420.008570640.0003469073.38362e-60.002455570.02862810.0009924430.0003918050.0008893210.003234640.02246535.87969e-57.72365e-50.001639660.006643730.002285030.01339490.00925190.001748860.01485260.01411790.006203430.02485480.01980890.01432997.61187e-70.01982520.0006979210.02306464.19578e-50.02884830.030750.02587140.001417210.0001067990.0001942650.0002979110.00903190.001627320.003142630.001210443.43582e-50.00814780.02000737.603e-50.007207730.001480990.007888110.01874510.003274740.002802820.001544490.0002625580.009921190.02245730.03439040.02715620.001565810.02139430.003060974.96002e-60.03211160.01833290.03705750.0001462460.01412081.46351e-52.84927e-50.0002615710.02141470.01794980.0002646460.006936529.44308e-60.001430150.00778764.46573e-50.03095740.005342090.0009919150.0002394410.009869820.004058880.0009260790.01412140.00361726⋯
80.01698510.01814060.02827720.01458530.0007002870.04982191.08348e-100.008202090.08324810.1365690.0003308980.003912470.1004970.0005161910.01177750.004258250.0003693044.33971e-70.03414290.01885920.01738070.0001863370.0003046860.0802470.01133516.72245e-50.0002457680.0005016860.01487910.006461890.01415960.004444440.002765810.02778270.02117270.008436410.02542520.1398020.01764628.47842e-80.08794910.005975980.08884758.19656e-60.08810710.02353210.02231520.01049721.91707e-50.0001676930.0006327920.07032010.003877440.00485260.002126231.38737e-50.01735250.04107992.18206e-50.0477470.00159230.004735370.0341410.007687340.03285860.0004462540.0001263270.01034630.06040460.03914710.01872260.0008213560.03062240.0009985333.77123e-50.02623090.02951650.05284950.0002298380.1183799.29935e-50.0002422090.0001017540.1124750.03089230.0001244230.01346111.43639e-60.004771660.00597145.43113e-60.0256840.03585740.001617710.0001893820.03619690.003791160.002140630.03942030.0119367⋯
90.01813440.006302080.009160490.01595520.000141590.0112025.61736e-80.008016140.002908950.001483280.0005452990.0001484980.001091510.0007050650.01713590.007255040.001813583.00538e-50.0004112930.007825430.0001901460.002991080.001919440.0001838590.00334540.0004945490.0002370380.001298470.006168230.002606740.01627620.006403240.003835950.01069730.01287420.009425520.01799810.0009535610.0151381.55504e-50.00391430.0003708760.004645760.0001838940.005590050.01134360.01705380.0006770340.0001424520.00143060.0008937070.001564210.002495740.005669610.002745850.0006881790.007217380.01054190.0007686790.001819830.004755080.01191510.01175620.003920240.0005536530.00104130.00238290.01453450.007790810.004877690.01088530.006211060.01495770.001668971.41714e-50.004752150.01313430.008456220.0007161370.0002906443.67577e-54.36755e-50.002116150.002767870.01228430.002392820.00726916.27152e-50.001637110.01447442.9771e-50.0134530.001571070.002574020.001761290.0043680.009765550.00177870.006874620.00292682⋯
100.01621370.007202130.009894830.01351920.0002252540.0111183.22505e-80.005893540.002514590.001520990.0007583810.0002371630.001328470.0009663420.0153920.00561630.00222262.33198e-50.0005827010.005512210.0002912470.003161040.001551580.0002573530.00201530.0006616640.000354320.0008806440.007080950.003271420.01607780.004771950.004574540.01130530.01331990.0102530.01634370.0009481220.01522591.31555e-50.004256530.0005505730.004889190.000143090.005516440.008671560.014630.0009539099.11381e-50.001748420.001202190.001923450.003132410.00653080.00337920.0008037910.008124560.01089580.0007450790.002270310.005439240.01053240.01209320.0047270.0007696820.0006798490.002590550.01470580.008108760.003583350.008203930.006112920.014710.001089162.61232e-50.00323040.01335440.007051130.0009591830.0002664946.35421e-57.55892e-50.002143830.002951940.01261730.002584760.008192114.86869e-50.002143310.01403121.55941e-50.01075120.002010980.003170760.002105180.005095380.01033410.002289680.007590360.00363169⋯
110.02676760.002165350.004273190.03177017.43672e-60.008080061.66518e-60.03465460.003819840.0006824877.25944e-56.58018e-60.0001946040.0001000920.02534120.02477030.0005355570.0001407423.19363e-50.03973239.50757e-60.002226580.005793441.31728e-50.03915219.31636e-52.01894e-50.009564260.002099950.0005406750.01393090.02658280.001177480.005717590.008060020.004720310.0235060.00049930.01142414.92183e-50.001475172.57224e-50.002128840.0007672110.003719820.03712010.03071686.29078e-50.001591210.0004505120.0001411270.0002807930.0005393120.002076610.0007037390.000325590.002739310.00614760.000989870.0003163740.001967520.02021260.00722470.001035784.91811e-50.009381180.001538770.01109010.004112270.01763810.03917720.006412350.01215990.01463343.48106e-70.02729390.008807390.0155140.0001242420.0002176051.29405e-61.42485e-60.002036590.001101980.007710760.001603540.002805890.0002811450.0002648850.0146910.0009788850.03468490.0002398950.0006685050.000632180.001219630.006134750.0003417960.00268850.000618432⋯
120.01757030.009455570.01251830.01411470.0003751070.01337922.26115e-80.005597640.002865370.001997240.001101340.0004104470.001961260.001394990.0166220.005460340.002891872.09748e-50.0009522860.005178660.0005030860.003623640.001510830.0004322270.001713820.0009062380.0005468070.0007751840.009289860.004564270.01862230.004536640.006002510.01403880.0161430.01269250.01805850.001231250.0179671.22936e-50.005644960.0008969060.006318580.00013210.006794240.00858780.0155230.00149827.53641e-50.002243890.001712160.002816050.004327030.008399450.004537380.0009630630.01051640.01344230.0007916490.003318310.006823610.01111890.01477770.006385080.001232790.0005843590.003017190.01724050.0102010.003555190.008013970.006783170.01730110.0009426144.74764e-50.003015070.01610060.00758770.001339150.0003346740.00011040.0001336660.002374350.003912550.01535470.002996080.01055294.4241e-50.003088760.01578931.13205e-50.01095620.002982420.004241250.002656030.006939740.01233130.003200560.009878130.00508172⋯
130.02372650.00619270.01118860.02462386.03249e-50.02139311.79681e-80.02077210.02070160.01034750.0001367850.0001354980.004337660.0002024070.01913440.01227070.000415729.07784e-60.0009460940.03469790.0003539850.0006444810.001537530.0009487750.02902597.04852e-56.01244e-50.002794020.005503160.001757620.01483460.01326090.001726740.01295790.0135340.006342310.02706620.009129530.0148892.25297e-60.01172170.0003426220.0143789.27368e-50.01953950.03587130.02983540.0007293940.0002278480.0002562650.000268630.004312810.00135510.003096270.001152146.33324e-50.006856690.01657650.0001528980.003729530.001720860.01088250.01638750.002704220.001160270.002663730.0004342190.01115820.01646310.0328780.03306810.002395490.02055640.004989762.79384e-60.03475580.01689380.03349330.0001513660.005826718.74143e-61.48792e-50.0004646740.01162290.01609990.0004413050.006096852.34148e-50.00103550.009935610.0001057260.03538090.002774380.0009775120.0003261360.006545930.004886730.0007896530.0104070.00257923⋯
⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋱
24890.1869483.22556e-50.01245510.0005069887.9098e-60.3455740.01335676.48624e-50.2308430.2106423.60048e-70.2307819.25411e-60.0869634.03705e-50.0002238910.1435740.1160070.1981270.05221290.0005150690.2124669.31717e-50.2135250.001699420.02651140.000314590.0003784670.2534990.1296890.1397350.3062270.1086430.01644640.00749665.9168e-50.2759850.001843650.329450.0007656453.25797e-50.003551140.1707710.07162830.04308640.1400250.0003121490.2119810.05885760.02228130.01853140.2159412.74433e-50.1991950.0004133840.001201520.12650.2334130.0004635030.117017.92475e-60.1928530.02438120.017290.04905520.2983930.07875133.91366e-60.0658190.2307070.1682020.0001394980.001014640.009247363.59103e-60.03411670.2820920.0163660.4016290.002808640.006554190.01043240.04023030.3414950.03536929.52398e-90.09579170.001059480.2512330.03000496.99025e-90.008758490.03677770.0001658570.2047980.004801670.3308752.29279e-50.01519051.80199e-6⋯
24900.00542760.02159710.03817490.004463432.62429e-50.00023630.03303930.02537780.001722140.001297683.47556e-70.001651913.33388e-60.007024710.001013420.03233380.007671865.76446e-50.00334240.01336290.03574830.001970020.002188820.002624510.02501340.01170980.0004078330.007820780.001539070.01124639.10016e-60.0004036850.007150090.0004512830.03010590.0001287390.001366351.96349e-50.0002220130.03139011.32759e-50.02692462.92917e-70.01119330.0187590.006010150.0297010.003559440.01547260.01924940.02819550.002358780.0144050.004768440.03055650.03807930.0003169680.0004554790.02451060.009881760.003536380.003995850.03269850.01742380.02407570.0007156050.01912750.008334760.009237220.0003251240.003014490.02915260.002465090.01426010.001347610.02934763.28188e-50.0004431281.87429e-60.02584750.02286550.001648050.0002051476.44099e-60.02981881.7407e-80.01366431.53648e-50.002103540.0107753.06263e-70.001600990.003337950.01809790.003059810.01440340.0002706320.000498350.01023750.00227582⋯
24910.08081990.0007943760.04252220.000625673.27847e-60.1686440.05554190.00130890.1730040.03372695.46804e-80.04972321.31159e-60.1660665.7273e-50.003072340.05669010.003336560.05419620.1290570.00482010.04402030.0001455670.05507130.004583390.0145750.0001331150.0007283730.1544820.09006730.003092730.06081570.1607030.001776860.01394852.58847e-50.101689.14718e-50.06150610.004127615.76758e-60.03868380.002505090.1407850.03125190.157490.002609340.07362510.1209930.09313490.024450.1648260.0003175290.09435840.003050730.007499660.007268430.02736830.01397720.1327764.18361e-50.1449930.06028280.01445190.08567230.07795950.07392977.0179e-50.1511330.02353160.03469420.002088280.000703530.008134871.45283e-50.04710620.02096190.001754990.03036580.03553440.05575120.00254920.002197470.024480.06387361.24435e-90.05469995.69092e-50.1155410.01505314.1856e-90.1351660.1773150.0009277760.05524870.0601460.06924882.7857e-50.009063071.29699e-5⋯
24920.03906560.0003806980.01663290.001167581.30548e-50.01397680.01598030.0006161060.02548980.02436493.77735e-70.02779396.35799e-60.02504080.0001450050.001423420.03942840.005180560.03396880.02430630.002458030.02873440.000322510.03205250.004583710.01776030.0003442820.001217360.02603910.04193410.002633470.01777690.02923490.0037680.01185078.09e-50.02706050.0002986640.01435440.003043342.31796e-50.006380830.000683930.02742310.02802310.03201030.001725280.03554930.02815410.01685510.01976160.0281070.0003104360.03797820.002068520.004217210.01078030.01680140.001780870.03588848.92234e-50.0332130.0233440.01601320.03121940.02196520.0388747.85112e-50.02373440.01458230.03031890.001034090.001400260.0102633.83422e-50.02827440.006181530.003730210.002166680.005422190.008576030.00478190.004691330.003399230.02840811.33612e-80.03910650.0001950180.03039360.01851033.44049e-80.003018920.01030650.001006470.0333430.005694690.01553517.83625e-50.01214783.10911e-5⋯
24930.03508450.0001025970.007425580.001324542.78005e-50.005944130.005944220.0001748830.0120380.03456021.35353e-60.03254872.01577e-50.009042470.0001785040.0004501640.0421290.01665890.03881030.008893080.0009053120.03624190.0003655820.03616870.003205330.02156790.0006122240.001157670.01380590.03222530.007183110.01641890.01228470.00927580.008663590.0001537520.02003090.001102560.01233090.001532096.37826e-50.001424670.001332010.01088680.02769440.01525830.0007296930.03405560.01184950.005191960.01568040.01400410.0001395950.03083040.00091710.001822160.02771070.02447990.0002648060.01914186.93808e-50.01872470.0114230.01652540.01652740.01842520.02869093.27307e-50.008248370.02222840.04307480.0003273730.001934730.01099263.51631e-50.01963010.007671620.009211750.001509030.00112220.002003490.008792540.01417950.003146480.0161375.98159e-80.03786810.0007170150.02096580.02318268.79976e-80.0002712660.001924330.0005856560.03767320.0009750440.01269590.0001053940.01496252.3116e-5⋯
24940.007303140.001364790.009913540.00462818.36574e-50.0001448450.006549480.001851080.0009575130.004333192.9396e-60.003983912.58399e-50.001943950.001066510.003136780.01275860.0009523080.007040860.003321340.004809830.005202030.002031890.005613690.01123550.01891290.001079860.005549930.001054980.01042130.0001446370.0008020460.002584080.00310050.01678870.0003581280.001640030.0002879140.0004229680.007408888.07881e-50.002070484.05854e-60.003352350.02177640.002791010.004820870.005648630.004804510.003166480.01999080.001370120.002133470.005571170.005503780.007231090.003048450.001805180.0007887080.00510.001288570.002637160.01079330.01975050.01009040.0011390.01480690.0009348260.002259680.001436980.008959720.002718530.004053290.01636760.0006529850.01788120.000137540.00306454.43305e-60.001721480.002062270.005822570.00236622.0616e-50.01318021.96258e-70.01738260.0002162590.002125520.01871599.83663e-74.30443e-50.0003151290.00483650.006417210.0008009030.0004656360.0006146110.01613820.000686994⋯
24950.05341640.003430850.06827710.00107634.41665e-60.06395470.08786840.005120820.09779320.01614595.59085e-80.02500091.14845e-60.1461990.000116860.009991290.04075550.0009373660.03168330.1383790.01356280.0229360.0002965860.0305310.009134530.01484720.0001558810.001482790.08310510.07325230.0006244690.02351050.1340850.001029330.02210413.28755e-50.05071824.28587e-50.02136750.01021315.24781e-60.07896260.000281520.1372860.0325590.1202230.00762370.04393430.1281410.125750.03245430.09885640.001235990.06106730.008485140.01808280.002772840.01071210.04188570.1123570.0001481930.09566260.08301640.01730850.09827230.03380390.07215810.0003509490.1470220.008660490.01996110.007236810.0009465280.01043694.89609e-50.05759850.00514570.001013940.004592680.07568880.09900690.002068550.0009291170.004550590.07974481.38248e-90.0471342.81356e-50.06363580.01474178.60394e-90.162110.1725120.002670230.03167230.1080580.02502475.48545e-50.00991275.52636e-5⋯
24960.00537140.003250880.01385910.003521133.98377e-50.0001571060.0103110.004176510.001048220.002203999.36643e-70.002325168.66337e-60.0027790.0007948290.0063480.008497580.0002524490.004304270.004894370.008544350.002909970.001599470.003424140.01215360.01239320.0005640360.004911040.001058690.00886174.00791e-50.0005205680.003303550.001133820.01684670.0001818490.001297767.70406e-50.0002820860.01041592.99977e-50.00481921.2535e-60.004591060.0164450.003222950.007867680.00389960.006432760.00547850.01833730.001464390.003538010.004364970.008619540.01119940.0009970020.0008665750.002598050.005576690.001455450.002645140.01376770.01489680.01177820.0008064490.01341130.001713590.003380290.0006612250.004721310.005567560.002575140.01220820.0006541920.0176416.69906e-50.001117712.88358e-60.004250570.004530430.002765560.0007089231.15555e-50.0149275.47986e-80.0128155.86454e-50.001797950.01192094.50764e-70.0001654640.0007134880.006361090.003936960.002169650.0003235660.0004287490.01062430.000829364⋯
24970.006480170.0002088480.003227540.005136490.0002181055.02761e-50.001677570.0003060470.0003684220.007238651.56234e-50.005143630.0001184410.0005043840.00129880.000608170.01413690.004920060.008681730.0008616040.001155340.007384970.002219160.006841390.006493430.02406170.002246310.004806170.0004750820.007388070.0006190670.0007745410.0008230830.01055260.01050140.0008075570.001155650.00170590.0003746880.002720610.000306030.0002640871.17245e-50.000976920.02105850.001058520.001385610.005508280.001501440.0006410760.01415530.0005628620.000648210.004333590.001690980.002174680.01140070.003180815.68144e-50.002223510.0008142130.001264830.004021420.01997490.004239890.0009587040.009791540.000251330.0005524150.002702520.01475620.000524820.005966570.01728170.0005154050.01069040.0002043450.01047613.20437e-60.0001978780.0002827360.01307840.01086222.1309e-50.006033061.38963e-60.0166410.001268410.001352480.02488853.14678e-61.72853e-63.38924e-50.002122040.007810657.27477e-50.0003848260.0008440230.02078780.000402443⋯
24980.1784563.63052e-60.00370170.0004504711.63895e-50.1648790.003205568.0585e-60.1078340.3921481.54324e-60.3351623.62526e-50.02499493.71587e-53.39065e-50.1637150.7026860.2642420.01417739.88042e-50.3329387.77088e-50.2860970.0007997520.03100790.0005527180.0002556810.1385850.09510120.784390.3683620.03821160.05535380.00404930.0001092830.2316580.01091810.3778290.0002241730.0001061420.0004201970.7936380.02221670.03901840.05921326.9731e-50.2270610.01899650.004519390.01179030.1052535.93723e-60.169729.95173e-50.0002955820.5230710.4833382.92136e-50.05452523.42782e-60.1052810.008561480.01566780.02025290.3064920.05143767.04928e-70.01741360.5159480.2931982.06623e-50.001250810.008543381.92892e-60.01905580.5720650.05534670.4863150.0002986670.000862010.02184110.1945790.5394050.01540425.17345e-80.0907810.006121330.18680.03695111.54487e-80.0004223170.004612185.46626e-50.2714580.0004328980.352242.37814e-50.01760456.8995e-7⋯
24990.004162510.0001425830.001961180.005903370.0003382341.54751e-50.000899290.0002067190.0001452480.005414233.00222e-50.003472250.000196040.0002038050.001699670.0004055680.01055830.004931040.006171630.0003836580.0007971180.005316110.002750660.004710550.005821180.02284180.002909190.005312370.0001974880.004707370.0004805770.0003981560.0003582790.01230640.008741560.001132650.000576870.002353590.0001751270.002170860.0004699990.0001139145.6187e-60.0004395650.01766190.000480530.001063780.003524280.0007282550.0002831030.01147660.0002359630.0005891570.002582190.001309360.001552950.01133390.002211512.23586e-50.001137380.001012750.0005997660.002420810.01834530.002474470.000487430.006596150.0002433790.000227710.001882170.01200020.0003603650.00698020.0167710.000697870.007658590.000103790.01222748.9926e-78.28168e-50.0001179820.01467930.01256547.89382e-60.003829093.20365e-60.01264680.001788010.0006742280.02368196.64705e-63.24864e-79.3284e-60.001991240.005464022.49331e-50.0001772390.001151420.0205630.00052827⋯
25000.005248830.0006033370.005226720.004377450.0001128426.08632e-50.003079360.0008335930.0004532280.003950315.26329e-60.00324884.2004e-50.0008284330.001085880.001472320.01032440.001337150.005772540.001465830.002431470.004462390.001965820.004534360.008045850.01736810.001278660.00481780.0005326790.006998960.0001753980.0005450820.001200280.004075590.01197580.0004467320.001006820.000472010.000270910.004462280.0001209730.0007357843.69127e-60.001535870.01766610.00138430.002667680.004166070.002307770.001296970.01464040.0006757360.001275020.003751460.003114420.003949570.003887310.001627760.000229880.002749420.001065640.001422010.005896850.0167720.005644340.000740990.009944220.0005517480.0009533910.001321190.00838390.001287940.004186550.0143560.0005937880.01192580.000105410.004034622.22714e-60.0005872080.0007394230.00669440.003381411.26956e-50.007789564.07699e-70.01356920.0003562520.001266350.01742321.57372e-68.11584e-69.06461e-50.003251510.005211260.0002374690.0002907680.0006576780.01509580.000566752⋯

Problem 1(e)¶

Let $\hat{s}_{jt}$ denote the predicted market share of product $j$ at time $t$, which is given by:

$\hat{s}_{jt} (\delta_t, \theta_2) = \int \frac{\exp(\delta_{jt} + \mu_{ijt}(\theta_2))}{1 + \sum_k \exp(\delta_{kt} + \mu_{ikt}(\theta_2))} dF_t(i)$

where $\theta_2$ denotes the non-linear parameters of this model, $\delta_t$ is the vector of mean utilities of all products, and $F_t(i)$ denotes the distribution of consumer characteristics in market $t$.

Given that we have a sample of 500 consumers drawn from $F_t(i)$, we can approximate the integral over $F_t(i)$ by summing over all consumers in market $t$:

$\hat{s}_{jt} (\delta_t, \theta_2) \approx \sum_{i \in \mathcal{S}_t} s_{ijt} = \sum_{i \in \mathcal{S}_t} \frac{\exp(\delta_{jt} + \mu_{ijt}(\theta_2))}{1 + \sum_{k \in \mathcal{J}_t} \exp(\delta_{kt} + \mu_{ikt}(\theta_2))}$

Where $\mathcal{S}_t$ denotes the set of simulated consumers.

Write a function that aggregates the individual choice probabilities of all consumers to compute the predicted market shares for each product, as a function of $\delta_t = (\delta_{1t}, \ldots, \delta_{J_t,t})$ and $\theta_2 = (\alpha, \sigma_1, \sigma_2)$. Given nonlinear parameters $\alpha^y = 0$, $\sigma_1^y = 1$, $\sigma_2^y = 1$, the vector $\delta_t^0$ from Problem 1(d), and the sample of simulated consumers you obtained in part 1 (b), compute $\hat{s}_{jt}(\delta_t^0, \theta_2^y)$ for all products and all markets. Compute $\bar{p}^{''' } = \sum_j p_{jt} \hat{s}_{jt}(\delta_t^0, \theta_2^y)$ and $\text{cor}(\bar{p}^{'''}, \bar{y}_t)$. Compare the correlation between the average prices paid by consumers predicted by the model and those observed in the data (from Problem 1(a)). What does the difference between these results suggest about the true value of $\alpha$?

In [7]:
function s_jt_hat(simulated_consumers::DataFrame, delta_table::DataFrame, product_data::DataFrame, nonlinear_param::Dict{Symbol, Float64})
    
    alpha = nonlinear_param[:alpha]
    sigma_1 = nonlinear_param[:sigma_1]
    sigma_2 = nonlinear_param[:sigma_2]
    
    product_variables = innerjoin(delta_table, product_data, on = [:product_ID, :t])
    
    grouped_simulated = groupby(simulated_consumers, :t)
    grouped_product = groupby(product_variables, :t)

    product_shares_all = DataFrame()
    
    for tt in 1:length(grouped_product)
        
        data = sort(grouped_product[tt], :product_ID)
        n_j = nrow(data)
        
        consumer_census_t = sort(grouped_simulated[tt], :consumer_ID)
        
        income_data = transpose(repeat(consumer_census_t.income, 1, n_j))
        sugar_taste = transpose(repeat(consumer_census_t.nu_1, 1, n_j))
        caffeine_taste = transpose(repeat(consumer_census_t.nu_2, 1, n_j))
        
        mu_ijt = alpha .* data.price .* income_data .+ sigma_1 .* sugar_taste .* data.sugar .+ sigma_2 .* caffeine_taste .* data.caffeine
        utility = mu_ijt .+ data.delta
        
        # Calculate utility from outside option
        outside_option = zeros(size(utility, 2))     
       
         # Calculate inclusive values (log-sum-exp over rows)
        inclusive_values = log.(sum(exp.(vcat(utility, outside_option')), dims=1))
        
        current_shares = exp.(utility .- inclusive_values)
        
        product_shares = sum(current_shares, dims=2) ./ nrow(consumer_census_t)
        
        current_shares_df = DataFrame(product_shares, [:s_jt_hat])

        current_shares_df.product_ID = data.product_ID
        current_shares_df.t = fill(tt, nrow(current_shares_df))
        
        append!(product_shares_all, current_shares_df)
        
    end
    
    return product_shares_all
    
end
Out[7]:
s_jt_hat (generic function with 1 method)
In [8]:
predicted_shares = s_jt_hat(sample, delta_table, product_data, theta_2_double_prime)

product_comb = innerjoin(product_data, predicted_shares, on=[:product_ID, :t])

# Add market_share column to product_comb DataFrame
product_comb[!, :market_share] = product_comb[!, :s_jt_hat]

grouped_product = groupby(product_comb, :t)
p_bar = combine(grouped_product) do sdf
    DataFrame(p_bar = mean(sdf.price .* sdf.market_share))
end

market_data = innerjoin(mean_income, p_bar, on = :t)

correlation = cor(market_data.mean_income, market_data.p_bar)
println(correlation)
0.044607516356691856

Problem 2(a)¶

Let $s_{jt}$ be the market shares for product $j$ in market $t$ observed in the data, and $\hat{s}_{jt} (\delta_t, \theta_2)$ be the market shares predicted by the model. Berry (1994) shows that, given $\theta_2$, there exists a unique vector $\hat{\delta}_t (\theta_2)$ that equates the observed and the predicted market shares:

$$s_{jt} = \hat{s}_{jt} \left( \hat{\delta}_t (\theta_2) , \theta_2 \right)$$

In order to find the vector $\hat{\delta}_t (\theta_2)$ that equates the observed and the predicted market shares, we can use the following contraction mapping:

$$\delta_{jt}^{(\tau+1)} = \delta_{jt}^{(\tau)} + \log(s_{jt}) - \log\left( \hat{s}_{jt} \left( \delta_{jt}^{(\tau)}, \theta_2 \right) \right)$$

where $\delta_{jt}^{(\tau)}$ denotes the current-period guess for $\hat{\delta}_{jt} (\theta_2)$. Write a function that employs this contraction mapping (or one of the alternatives discussed in Conlon & Gortmaker (2020)) to find $\hat{\delta}_t (\theta_2)$ for any given $\theta_2$.

In [9]:
function delta_inversion(delta_initial, next_delta, tolerance)
    delta_t = delta_initial

    while norm((delta_t) .- next_delta(delta_t)) > tolerance
        delta_t = next_delta(delta_t)
    end

    return delta_t
end

function delta_hat(nonlinear_param, product_data, simulated_consumers, tolerance)
    
    each_period_product_data = groupby(product_data, :t)
    each_period_census = groupby(simulated_consumers, :t)
    
    T = length(each_period_product_data)
    
    final_delta = DataFrame()
    
    function processPeriod(tt)
        current_period_var = sort!(each_period_product_data[tt], :product_ID)
        consumer_census_tt = sort!(each_period_census[tt], :consumer_ID)
        
        current_period_var[!, :delta] = log.(current_period_var[!, :market_share]) .- log(1 - sum(current_period_var[!, :market_share]))
        
        delta_initial = select(current_period_var, :product_ID, :delta, :t)
        
        select!(current_period_var, Not(:delta))
        
        s_jt_obs = current_period_var[!, :market_share]

        current_period_var_df = DataFrame(current_period_var)
        consumer_census_tt_df = DataFrame(consumer_census_tt)

function next_delta(par)
            delta_current = DataFrame(product_ID = delta_initial[!, :product_ID], delta = par, t = delta_initial[!, :t])
            
            # Compute predicted shares using current delta
            s_jt_mod = s_jt_hat(consumer_census_tt_df, delta_current, current_period_var_df, nonlinear_param)
            sort!(s_jt_mod, :product_ID)
            s_jt_pred = s_jt_mod[!, :s_jt_hat]
            
            # Update delta
            delta_new = delta_current[!, :delta] .+ log.(s_jt_obs) .- log.(s_jt_pred)
            
            return delta_new
        end

        result = delta_inversion(delta_initial[!, :delta], next_delta, tolerance) 
        
        delta_current = DataFrame(product_ID = delta_initial[!, :product_ID], delta = result, t = delta_initial[!, :t])
        
        return delta_current
    end
    
    for tt in 1:T
        delta_result = processPeriod(tt)
        append!(final_delta, delta_result)
    end
    
    return final_delta
end
Out[9]:
delta_hat (generic function with 1 method)

Problem 2(b)¶

In this exercise, we will study how the accuracy of $\hat{\delta}_t (\theta_2)$ changes depending on the size of our sample of simulated consumers. As before, let $\theta_2^y = (0, 1, 1)$. For market $t = 1$ and $n = 1, 2, \ldots, 100$, draw a sample $\mathcal{S}_n$ of consumers using the function you wrote for Problem 1(a), each of them containing $S_n = 100$ simulated consumers (100 different samples, each sample must include 100 consumers). For each sample $\mathcal{S}_n \in \{\mathcal{S}_1, \mathcal{S}_2, \ldots, \mathcal{S}_{100}\}$, let

$$\hat{\delta}_n(\theta_2^y) = \left( \hat{\delta}_{1t_n}(\theta_2^y), \ldots, \hat{\delta}_{J_t,t_n}(\theta_2^y) \right)$$

  1. Plot the distribution of $\hat{\delta}_{1t_n}(\theta_2^y)$.

  2. Report the sample mean:

$$\bar{\delta}_{1t} = \frac{1}{100} \sum_{n=1}^{100} \hat{\delta}_{1t_n}(\theta_2^y)$$

  1. Report the sample variance

$$\frac{1}{100} \sum_{n=1}^{100} \left( \hat{\delta}_{1t_n}(\theta_2^y) - \bar{\delta}_{1t} \right)^2$$

  1. Repeat 1, 2, and 3 increasing the size of each sample from 100 to 500. How do the results from parts 2(a) and 2(b) compare to each other?
In [10]:
function delta_hat_sim(nonlinear_param, product_data, n_sim, n_salmple)
    
    first_market_data = product_data[product_data.t .== 1, :]
    
    function compute_delta(i)
        
        sample_i = simulate_consumers(consumer_census, n_salmple, i)
        
        first_market_consumers = sample_i[sample_i.t .== 1, :]
        
        delta_hat_i = delta_hat(theta_2_double_prime, first_market_data, first_market_consumers, 1e-8)
        
        delta_i_1 = delta_hat_i[!, :delta][1]
        
        return(delta_i_1)
        
    end
    
    results = zeros(n_sim)  # create an empty array that can hold any type
    
    for j in 1:n_sim
        
        results[j] = compute_delta(j)
        
    end
    
    return(results)
    
end
Out[10]:
delta_hat_sim (generic function with 1 method)
In [11]:
delta_tilde_1 = delta_hat_sim(theta_2_double_prime, product_data, 100, 100)

mean(delta_tilde_1)
Out[11]:
3.005090488551078
In [12]:
var(delta_tilde_1)
Out[12]:
0.8992948086119623
In [13]:
histogram(delta_tilde_1, bins=30, label="delta_tilde_1", alpha=0.6, color=:blue)
Out[13]:
No description has been provided for this image
In [14]:
delta_tilde_2 = delta_hat_sim(theta_2_double_prime, product_data, 100, 500)

mean(delta_tilde_2)
Out[14]:
2.872556452151993
In [15]:
var(delta_tilde_2)
Out[15]:
0.14957281962634364
In [16]:
histogram(delta_tilde_2, bins=30, label="delta_tilde_2", alpha=0.6, color=:blue)
Out[16]:
No description has been provided for this image

Problem 3(a)¶

In this problem, we will follow Gandhi and Houde (2023) to construct differentiation instruments $A_j (x_t, w_t)$ using the products' observed characteristics

$$x_{jt} = (1, sug_{jt}, caf_{jt})$$

and price instruments

$$w_{jt} = (\text{corn\_syrup\_price}_t \times sug_{jt}, \text{caffeine\_extract\_price}_t \times caf_{jt})$$

Construct the instruments $A_j (x_t, w_t)$

In [17]:
function build_GH_instruments(product_data, mean_income)
    # Copy product_data
    dd = copy(product_data)
    
    # Fit the model and predict
    model = lm(@formula(price ~ sugar * corn_syrup_price + caffeine * caffeine_extract_price), dd)
    dd.p_hat = predict(model)

    # Creating pairwise combinations
    dd_pairs = innerjoin(dd, dd, on = :t, makeunique=true, validate=(false, false))
    dd_pairs = filter(row -> row.product_ID ≠ row.product_ID_1, dd_pairs)

    # Calculate squared differences for sugar, caffeine, and p_hat
    dd_pairs[!, :sq_diff_sugar] = (dd_pairs[!, :sugar] .- dd_pairs[!, :sugar_1]).^2
    dd_pairs[!, :sq_diff_caffeine] = (dd_pairs[!, :caffeine] .- dd_pairs[!, :caffeine_1]).^2
    dd_pairs[!, :sq_diff_p_hat] = (dd_pairs[!, :p_hat] .- dd_pairs[!, :p_hat_1]).^2

    # Aggregate these differences by product_ID and t
    aggregated_diff_sugar = combine(groupby(dd_pairs, [:product_ID, :t]), 
                                    :sq_diff_sugar => sum => :GH_instrument_sugar )
    aggregated_diff_caffeine = combine(groupby(dd_pairs, [:product_ID, :t]), 
                                       :sq_diff_caffeine => sum => :GH_instrument_caffeine )
    aggregated_diff_p_hat = combine(groupby(dd_pairs, [:product_ID, :t]), 
                                    :sq_diff_p_hat => sum => :GH_instrument_p_hat )

    # Join aggregated results back to the original DataFrame
    dd = leftjoin(dd, aggregated_diff_sugar, on = [:product_ID, :t])
    dd = leftjoin(dd, aggregated_diff_caffeine, on = [:product_ID, :t])
    dd = leftjoin(dd, aggregated_diff_p_hat, on = [:product_ID, :t])

    # Merging with mean_income and other computations
    instrument_data = innerjoin(dd, mean_income, on=:t)
    instrument_data.avg_income_inst = instrument_data.mean_income .* instrument_data.p_hat

    # Adding a constant column
    instrument_data.constant = ones(nrow(instrument_data))

    return instrument_data
end
Out[17]:
build_GH_instruments (generic function with 1 method)
In [18]:
instrument_data = build_GH_instruments(product_data, mean_income)
Out[18]:
2500×16 DataFrame
2475 rows omitted
Rowproduct_IDpricesugarcaffeinecorn_syrup_pricecaffeine_extract_pricequantitytmarket_sharep_hatGH_instrument_sugarGH_instrument_caffeineGH_instrument_p_hatmean_incomeavg_income_instconstant
Int64Float64Float64Float64Float64Float64Int64Int64Float64Float64Float64?Float64?Float64?Float64Float64Float64
112.021331.580866.074460.1990220.26489922310.02231.92786298.94191.76377.510156.0025911.57211.0
211.941212.408835.372990.1896510.26338610620.01061.87266183.953.10367.742654.55028.520981.0
311.650121.374394.791420.1905190.2836228130.00811.62128342.57635.699718.60425.92959.613361.0
411.651041.8295.402060.1967380.2347517840.00781.63139317.57463.764718.91234.432527.231151.0
512.189071.157136.597570.314640.25025571250.07122.02285381.115157.93716.52044.451579.004851.0
611.162531.944254.572790.1746090.1820374360.00431.17332256.92458.79929.359025.57226.537981.0
711.705391.750747.436890.2902270.16153763470.06341.72901276.034357.13312.85154.854868.394111.0
811.682181.18324.273150.2042260.31491913180.01311.58654443.93562.600435.50524.510547.156171.0
911.726472.364645.29340.261210.242201890.00081.90328211.13272.428713.7034.783929.105131.0
1011.997821.557315.140660.2201580.299709243100.02431.88404302.39138.345216.6455.18519.768941.0
1111.740072.003234.537690.2053430.29035548110.00481.72775253.60157.718319.93834.80548.302541.0
1212.063382.300175.297680.2396240.28222949120.00492.04745176.0847.259612.08845.9662212.21551.0
1311.403131.63474.235230.3483980.21337115130.00151.47531284.63112.83651.56434.693446.924281.0
⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮⋮
2489503.139895.723396.284770.2369560.278179306390.03063.10466410.487.578140.57075.9363518.43041.0
2490501.929625.180984.03550.1164540.308221235400.02351.83187298.78592.97165.942315.8479110.71261.0
2491502.098913.802184.81430.2407110.21996586410.00861.97515176.07452.453310.61795.4293210.72371.0
2492503.522636.440616.668560.314820.247241291420.02913.68829584.269196.069112.6434.7702117.59391.0
2493503.479468.205513.967250.2883530.2021053913430.39133.169261363.4190.964788.19335.7444518.20561.0
2494502.365074.212254.262670.2740550.27937152440.00522.34486151.35878.012613.5975.5405812.99191.0
2495502.356233.570385.41920.3214090.22268629450.00292.36198145.94469.810618.85154.2839510.11861.0
2496502.19764.293594.132980.243890.26536376460.00762.14135162.41157.558111.90515.6543512.10791.0
2497502.223134.763125.11240.1798160.28441922470.00222.30425229.07355.968111.59025.5555412.80141.0
2498502.861814.961896.099990.3071710.22780266480.00662.92356235.3104.61840.58045.5676316.27731.0
2499502.292454.229634.785520.2515690.24075110490.0112.21666166.05645.646110.1545.0219111.13191.0
2500502.017273.825394.590950.2105640.25506263500.00631.97377171.14877.84712.74675.9439811.73211.0

Problem 3(c)¶

Code the GMM objective function that you would use to estimate the nonlinear parameters $\theta_2$, using the instruments you derived in part (a). Evaluate the objective function at $\tilde{\theta} = (-0.5, 2, 2)$.

In [19]:
function GMM_objective(par,product_data,sample,mean_income)
    
    theta = Dict(
    :alpha => par[1],
    :sigma_1 => par[2],
    :sigma_2 => par[3]
)
    
    N = nrow(product_data)
    
    delta_table = delta_table = delta_hat(theta, product_data, sample, 1e-6)
    
    demand_instruments = build_GH_instruments(product_data, mean_income)
    
    sort!(product_data, [:t, :product_ID])
    sort!(delta_table, [:t, :product_ID])
    sort!(demand_instruments, [:t, :product_ID])
    
    X = hcat(product_data[!, :price], product_data[!, :sugar], product_data[!, :caffeine], ones(size(product_data, 1)))
    
    Z  = hcat(
    demand_instruments[!, :sugar], demand_instruments[!, :caffeine],demand_instruments[!, :p_hat],
    demand_instruments[!, :GH_instrument_sugar],demand_instruments[!, :GH_instrument_caffeine],
    demand_instruments[!, :avg_income_inst],demand_instruments[!, :constant]
)

    #fix type just in case
    Z = Matrix{Float64}(Z)
    
    delta = hcat(delta_table[!, :delta])

    W = inv((Z' * Z) / N)
    
    P_Z = Z * inv(Z' * Z) * Z'
    
    Beta_2sls = inv(X' * P_Z * X) * X' * P_Z * delta
    
    xi_hat = delta - X * Beta_2sls
    
    g = ( Z' * xi_hat ) / N
    
    objective_value = g' * W * g
    
    return objective_value[1]
    
end
    
Out[19]:
GMM_objective (generic function with 1 method)
In [20]:
GMM_objective([-0.5,2,2],product_data,sample,mean_income)
Out[20]:
1.1737387832864838

Problem 3(d)¶

Write a function that computes the analytic gradient as a function of the vector of nonlinear parameters $\theta_2$.

The gradient of the GMM objective function is

$$\nabla q (\theta_2) = 2G(\theta_2)^T W g (\theta_2)$$

with

$$G (\theta_2) = \frac{1}{N} \underbrace{Z^T}_{T \times 3} \underbrace{\frac{\partial \xi}{\partial \theta_2}}_{T \times N \times 3}$$

$$\frac{\partial \xi}{\partial \theta_2} = \frac{\partial \delta}{\partial \theta_2}$$

$\frac{\partial \delta}{\partial \theta_2}$ can be separated by market $t$, after using the implicit function theorem:

$$\frac{\partial \delta_t}{\partial \theta_2} (\theta_2) = - \left( \frac{\partial \hat{s}_t}{\partial \delta_t} (\theta_2) \right)^{-1} \left[ \frac{\partial \hat{s}_t}{\partial \theta_2} (\theta_2) \right]$$

$$\underbrace{}_{J_t \times 3} \qquad \underbrace{}_{J_t \times J_t} \qquad \underbrace{}_{J_t \times 3}$$

$$\frac{\partial \hat{s}_t}{\partial \delta_t} (\theta_2) = \begin{bmatrix} \frac{\partial s_{1t}}{\partial \delta_{1t}} & \cdots & \frac{\partial s_{1t}}{\partial \delta_{J_t,t}} \\ \vdots & \ddots & \vdots \\ \frac{\partial s_{J_t,t}}{\partial \delta_{1t}} & \cdots & \frac{\partial s_{J_t,t}}{\partial \delta_{J_t,t}} \end{bmatrix}$$

With

$$\frac{\partial \hat{s}_{jt}}{\partial \delta_{kt}} = \int \frac{\partial s_{ijt}}{\partial \delta_{kt}} dF(i)$$

$$= \int s_{ijt} (1 - s_{ijt}) dF(i) \text{ if } j = k$$

$$= \int -s_{ijt} s_{ikt} dF(i) \text{ if } j \neq k$$

In [21]:
function partial_s_delta(product_data::DataFrame, simulated_consumers::DataFrame, theta_2::Vector, time_period::Int)
    # Assuming theta_2 is a vector with at least 3 elements
    nonlinear_param = Dict(
        :alpha   => theta_2[1],
        :sigma_1 => theta_2[2],
        :sigma_2 => theta_2[3]
    )
    
    # Filter product_data for the given time_period
    product_data_t = product_data[product_data.t .== time_period, :]

    delta_table = delta_hat(nonlinear_param, product_data_t, simulated_consumers, 1e-7)

    # You need to define or import the s_ijt function in Julia
    individual_shares_t = s_ijt(simulated_consumers, delta_table, product_data_t, nonlinear_param)

    # Assuming `product_ID` is a column in `individual_shares_t`
    individual_shares_t = individual_shares_t[sort(individual_shares_t.product_ID), :]

    deriv_matrix_t = zeros(size(individual_shares_t, 1), size(individual_shares_t, 1))

    diag_t = zeros(50)
    
    for i in 1:size(individual_shares_t, 1) - 2
        # Assuming individual_shares_t[i, :] gets the i-th column representing a consumer
        consumer_i = DataFrame(product_ID = individual_shares_t.product_ID, market_share = individual_shares_t[:, i])
        consumer_i.market_share = convert.(Float64, consumer_i.market_share)
        deriv_matrix_t_i = -1 * consumer_i.market_share * transpose(consumer_i.market_share)
        deriv_matrix_t += deriv_matrix_t_i

        diag_i = consumer_i.market_share .* (1 .- consumer_i.market_share)
        diag_t += diag_i
    end

    for i in 1:size(deriv_matrix_t, 1)
        deriv_matrix_t[i, i] = diag_t[i]
    end

    return deriv_matrix_t / 500
end
Out[21]:
partial_s_delta (generic function with 1 method)

$$\frac{\partial \hat{s}_t}{\partial \theta_2} (\theta_2) = \begin{bmatrix} \frac{\partial s_{1t}}{\partial \alpha} & \frac{\partial s_{1t}}{\partial \sigma_1} & \frac{\partial s_{1t}}{\partial \sigma_2} \\ \vdots & \vdots & \vdots \\ \frac{\partial s_{J_t,t}}{\partial \alpha} & \frac{\partial s_{J_t,t}}{\partial \sigma_2} & \frac{\partial s_{J_t,t}}{\partial \sigma_2} \end{bmatrix}$$

$$\frac{\partial \hat{s}_{jt}}{\partial \alpha^y} = \int y_{it} p_{jt} s_{ijt} (1 - s_{ijt}) - y_{it} \left( \sum_{k \neq j} p_{kt} s_{ikt} \right) dF(i)$$

$$\frac{\partial \hat{s}_{jt}}{\partial \sigma_1} = \int \nu_{1it} sug_{jt} s_{ijt} (1 - s_{ijt}) - \nu_{1it} \left( \sum_{k \neq j} sug_{kt} s_{ikt} \right) dF(i)$$

$$\frac{\partial \hat{s}_{jt}}{\partial \sigma_2} = \int \nu_{2it} caf_{jt} s_{ijt} (1 - s_{ijt}) - \nu_{2it} \left( \sum_{k \neq j} caf_{kt} s_{ikt} \right) dF(i)$$

In [22]:
function partial_s_theta(product_data::DataFrame, simulated_consumers::DataFrame, theta_2::Vector, time_period::Int)
    nonlinear_param = Dict(
        :alpha   => theta_2[1],
        :sigma_1 => theta_2[2],
        :sigma_2 => theta_2[3]
    )

    product_data_t = product_data[product_data.t .== time_period, :]

    delta_table = delta_hat(nonlinear_param, product_data_t, simulated_consumers, 1e-7)

    individual_shares_t = s_ijt(simulated_consumers, delta_table, product_data_t, nonlinear_param)
    individual_shares_t = individual_shares_t[sort(individual_shares_t.product_ID), :]

    deriv_matrix_theta_t = zeros(size(individual_shares_t, 1), 3)

    for i in 1:size(individual_shares_t, 1) - 2
        consumer_i = DataFrame(
            product_ID = individual_shares_t.product_ID, 
            market_share = individual_shares_t[:, i],
            income = simulated_consumers.income[i],
            nu_1 = simulated_consumers.nu_1[i],
            nu_2 = simulated_consumers.nu_2[i]
        )
        
        select!(product_data_t, :product_ID, :price, :sugar, :caffeine)

        consumer_i = innerjoin(consumer_i, product_data_t, on = :product_ID)
        
        consumer_i.market_share = convert.(Float64, consumer_i.market_share)

        consumer_i.own_partial_alpha = consumer_i.income .* consumer_i.price .* consumer_i.market_share .* (1 .- consumer_i.market_share)
        consumer_i.cross_partial_alpha = consumer_i.income .* (sum(consumer_i.price .* consumer_i.market_share) .- consumer_i.price .* consumer_i.market_share)
        consumer_i.partial_alpha = consumer_i.own_partial_alpha .- consumer_i.cross_partial_alpha .* consumer_i.market_share

        consumer_i.own_partial_sigma_1 = consumer_i.nu_1 .* consumer_i.sugar .* consumer_i.market_share .* (1 .- consumer_i.market_share)
        consumer_i.cross_partial_sigma_1 = consumer_i.nu_1 .* (sum(consumer_i.sugar .* consumer_i.market_share) .- consumer_i.sugar .* consumer_i.market_share)
        consumer_i.partial_sigma_1 = consumer_i.own_partial_sigma_1 .- consumer_i.cross_partial_sigma_1 .* consumer_i.market_share

        consumer_i.own_partial_sigma_2 = consumer_i.nu_2 .* consumer_i.caffeine .* consumer_i.market_share .* (1 .- consumer_i.market_share)
        consumer_i.cross_partial_sigma_2 = consumer_i.nu_2 .* (sum(consumer_i.caffeine .* consumer_i.market_share) .- consumer_i.caffeine .* consumer_i.market_share)
        consumer_i.partial_sigma_2 = consumer_i.own_partial_sigma_2 .- consumer_i.cross_partial_sigma_2 .* consumer_i.market_share

        deriv_matrix_theta_t[:, 1] .+= consumer_i.partial_alpha
        deriv_matrix_theta_t[:, 2] .+= consumer_i.partial_sigma_1
        deriv_matrix_theta_t[:, 3] .+= consumer_i.partial_sigma_2
    end

    return deriv_matrix_theta_t ./ 500
end


function evaluated_moments(par)
    
    theta = Dict(
    :alpha => par[1],
    :sigma_1 => par[2],
    :sigma_2 => par[3]
)
    
    N = nrow(product_data)
    
    delta_table = delta_table = delta_hat(theta, product_data, sample, 1e-6)
    
    demand_instruments = build_GH_instruments(product_data, mean_income)
    
    sort!(product_data, [:t, :product_ID])
    sort!(delta_table, [:t, :product_ID])
    sort!(demand_instruments, [:t, :product_ID])
    
    X = hcat(product_data[!, :price], product_data[!, :sugar], product_data[!, :caffeine], ones(size(product_data, 1)))
    
    Z  = hcat(
    demand_instruments[!, :sugar], demand_instruments[!, :caffeine],demand_instruments[!, :p_hat],
    demand_instruments[!, :GH_instrument_sugar],demand_instruments[!, :GH_instrument_caffeine],
    demand_instruments[!, :avg_income_inst],demand_instruments[!, :constant]
)
    
    delta = hcat(delta_table[!, :delta])

    Z = Matrix{Float64}(Z)
    W = inv((Z' * Z) / N)
    
    P_Z = Z * inv(Z' * Z) * Z'
    
    Beta_2sls = inv(X' * P_Z * X) * X' * P_Z * delta
    
    xi_hat = delta - X * Beta_2sls
    
    g = ( Z' * xi_hat ) / N
    
    return Dict(:g => g, :W => W)
    
end
Out[22]:
evaluated_moments (generic function with 1 method)
In [23]:
function Analytic_gradient(product_data::DataFrame, simulated_consumers::DataFrame, theta::Vector)
  
  # Split data on times (assuming product_data has a column `t` for time periods)
  each_period_data = groupby(product_data, :t)
  
  partial_delta_theta = []

  TT = length(each_period_data)

  # Process each time period
  for tt in 1:TT
    current_period_data = each_period_data[tt]
    current_period_data = DataFrame(current_period_data)

    # Assuming order function sorts the DataFrame and product_ID is a column in current_period_data
    sort!(current_period_data, :product_ID)
     
    partial_s_delta_t = partial_s_delta(current_period_data, simulated_consumers, theta, tt)
     
    partial_s_theta_t = partial_s_theta(current_period_data, simulated_consumers, theta, tt)
     
    partial_delta_theta_t = (- inv(partial_s_delta_t) * partial_s_theta_t)

    push!(partial_delta_theta, partial_delta_theta_t)
  end

  # Concatenate all results vertically
  partial_delta_theta = vcat(partial_delta_theta...)
  
  instruments = build_GH_instruments(product_data, mean_income)

  Z_D = Matrix(instruments[:, [:sugar, :caffeine, :p_hat, :avg_income_inst, :GH_instrument_sugar, :GH_instrument_caffeine, :constant]])
  
  G = (transpose(Z_D) * partial_delta_theta) / nrow(product_data)
  
  moments = evaluated_moments(theta) 
  
  g = moments[:g]
  W = moments[:W]
  
  gradient = 2 * transpose(G) * W * g
  
  return gradient
end


Gradient = Analytic_gradient(product_data,sample, [-0.5,2,2])
Out[23]:
3×1 Matrix{Float64}:
 -1913.6682930428492
   373.8989663611442
   417.549439473164

Problem 3(e)¶

Estimate the vector $\hat{\theta}_2$ such that

$$\hat{\theta}_2 = \arg \min_{\theta_2} q (\theta_2) = g_1 (\theta_2)^T W g_1 (\theta_2)$$

In [24]:
function SolveGMM(product_data, sample, initial_guess)
    
    GMM_problem = function(theta_hat)
        objective_value = GMM_objective(theta_hat,product_data,sample,mean_income)
        return objective_value
    end

    # Optimize using BFGS
    result = optimize(GMM_problem, initial_guess, LBFGS())
    
    return result
end
Out[24]:
SolveGMM (generic function with 1 method)
In [25]:
result = SolveGMM(product_data, sample, [0.00,0.5,0.5])

result.minimizer
Out[25]:
3-element Vector{Float64}:
 0.14069303403169534
 1.0535769259103636
 1.023221164523225