function v = findv(pB,pS,l,h,ph,beta);
% function v = findv(pB,pS,l,h,ph,beta);

% This MATLAB script accompanies the article
% "The Great Capitol Hill Baby-Sitting Co-op: Anecdote or Evidence for the Optimum Quantity of Money?"
% by Hens, Schenk-Hoppé, Vogt
% It calculates the maximal money holdings of the optimal policy for given parameters.

% Parameters
% 0 < pB < 1 : success probability when choosing "buy "
% 0 < pS < 1 : success probability when choosing "sell"
% l > 0: low time value (= 5 in the experiment)
% h > l: high time value (= 10 in the experiment)
% 0 < ph < 1: probability of high time value (= 0.5 or 0.2 in the experiment)
% 0 < beta < 1: discounting parameter (= 0.95 in the experiment)

% Output
% v is a vector containing the values of the solution to the Bellman equation (value function)

% Author: Klaus Reiner Schenk-Hoppé (E-mail: k.r.schenk-hoppe@leeds.ac.uk, Web: www.schenk-hoppe.net)
% Last update: January 9, 2006


pl = 1-ph;

m = ceil(log((1-beta+beta*pS)*l*pB/(h*(pS*beta+pB)))/log(beta)) + 1;
%maximum money holdings does not exceed m (upper bound)

% 0 to m money stocks possible
vold(1:m) = 0.5*h/(1-beta) .* ones(1,m);

for i = 1:60, % 60 is the number of iterations following Blackwells' contraction procedure
  vneu(1) = beta * pS * vold(2) + (1-pS) * vold(1);
  for j = 2: m-1,
    vneu(j) = beta * ph * max(pB * (h/beta + vold(j-1)) + (1-pB) * vold(j), pS * vold(j+1) + (1-pS) * vold(j)) + beta * pl * max(pB * (l/beta + vold(j-1)) + (1-pB) * vold(j), pS * vold(j+1) + (1-pS) * vold(j));
  end
  vneu(m) = beta * (pB * ((ph * h + pl * l)/beta + vold(m-1)) + (1-pB) * vold(m));
  vold = vneu;
end
v = vneu;

sellflag = 0;

for j = m-1:-1:2,
  if (pB * (h/beta + vold(j-1)) + (1-pB) * vold(j) == max(pB * (h/beta + vold(j-1)) + (1-pB) * vold(j), pS * vold(j+1) + (1-pS) * vold(j))),
  fprintf('m = %2.0f , Buy if h \t',j-1);
  else
  fprintf('m = %2.0f , Sell if h \t',j-1);
  end

  if (pB * (l/beta + vold(j-1)) + (1-pB) * vold(j) == max(pB * (l/beta + vold(j-1)) + (1-pB) * vold(j), pS * vold(j+1) + (1-pS) * vold(j))),
  fprintf('m = %2.0f , Buy if l \t',j-1);
  else
  fprintf('m = %2.0f , Sell if l \t',j-1);
  if (sellflag == 0),
    sellflag = 1;
    mmax = j;
  end
  end
  fprintf('\n');
end

  fprintf('m = 0 , Sell if h \t');
  fprintf('m = 0 , Sell if l \t');
  fprintf('\n\n');

  fprintf('maximum money holdings = %2.0f \n',mmax);
