Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Ask: Profit maximization using forvalues/foreach

    Hi,

    I am writing commands to find the optimal values for maximum profit, though encountering some errors.

    Basically, have those variables:
    p_i: loss probability of individual - exogenous, [0,1]
    L_i: loss amount of individual - exogenous, randomly distributed
    premium: insurance premium - interested variable
    quantity: number of individuals who decide to buy insurance - endogenous dependent on [premium-(L_i*p_i)]>=<0; quantity = f(premium, p_i,L_i)
    buying: dummy, =1 if [premium-(L_i*p_i)]=<0, and = 0 otherwise
    profit = premium*quantity - sum(L_i*p_i*buying)

    I want to have 2 loops: 1st loop is to set constant values for p_i; and 2nd loop is to set values for premium. The idea is: in the second loop, given a loss probability, the company decides which premium, which consequently change quantity and hence profit, to maximize profit => have premium* given one p_i; and then I want to repeat the sequence of commands for different values of p_i so that in the end I would have a collection of optimal (p_i, premium)

    I have used single loop forvalue i=1/100{...} to generate risk tolerance level and wealth of 100 individuals. But this one is double loops. And I am really confusing. I have tried to write this down, it didn't work indeed, so please have a look and rescue me please:

    foreach c=1/10{
    gen p_i`c'=uniform()
    bysort p_i`c': foreach m=1/100{
    gen premium`m'=floor(1000*runiform() + 1)
    replace L_i = floor(1000*runiform() + 1)
    replace buying=1 if premium<=L_i*p_i
    replace buying=0 if premium>L_i*p_i
    count if buying==1
    egen quantity= sum(buying==1)
    tab quantity
    gen profit_i=premium*buying-L_i*p_i*buying
    egen profit = sum(profit_i) if buying==1
    }
    }

  • #2
    I solved my problem:

    gen L_i = floor(1000*runiform() + 1)
    set more off, perm
    set obs 100
    forval c=1/9{
    gen p_i`c'=0.1*`c'
    forval m=1/20{
    gen premium`c'_`m'= 50*`m'
    gen buying`c'_`m'=.
    replace buying`c'_`m'=1 if premium`c'_`m'<=L_i*p_i`c'
    replace buying`c'_`m'=0 if premium`c'_`m'>L_i*p_i`c'
    count if buying`c'_`m'==1
    quietly egen quantity`c'_`m'= sum(buying`c'_`m'==1)
    quietly gen profit_i`c'_`m'=buying`c'_`m'*[premium`c'_`m'-L_i*p_i`c']
    egen profit`c'_`m' = sum(profit_i`c'_`m') if buying`c'_`m'==1
    }
    }
    sum profit*

    Cheers,
    Thanh

    Comment

    Working...
    X