<?php require('config.php'); require('SRC/macros.php');  
list ($home,$url,$users,$assign,$msg,$host,$sql,$MYCookie,$applet,$os)=courseAll();
$user_nbr=getaUserNbr($$MYCookie);
list ($user_name,$user_home,$user_url,$user_profile)=userid($user_nbr);

echo "
 <script>
	function go() {
		if(document.frmDropdowns.request.value != '') 
			document.frmDropdowns.submit();
	}
 </script>";
                                                # ----- Header
myheader("Portfolio manager",'..',$myPermit);

echo "This is a tool performing a quantitative analysis of a portfolio, 
  with investments that are diversified in assets with multiple currencies.
  Use the <a href=\"http://finance.yahoo.com/l\">symbol search utility</a> 
  from yahoo to identify tickers for most of the shares quoted on the 
  <a href=\"http://finance.yahoo.com/exchanges\">major world markets</a>
  (e.g. <i>nesn.vx</i> for Nestle quoted on VTX) and <b>choose a short 
  time interval</b> to start with a limited amount of data for download.
  More information from <a href=PTF_help_tag.php>this link</a>.";
  if ($user_nbr<=99) {
    echo " You need to <a href=\"../login.php\">login</a> to be able to
      modify any of the data.";
  }
echo "<br>";

$db = SQLconnect($host, $sql);                  # ----- Default values
if (substr($os,0,6)=="Sun5.8") $wget='/usr/local/bin/wget';
else $wget='wget';
                                                # Time interval
if (!isset($from) || $user_nbr<=99) $from=(date("Y")-1).date("-m-d");
if (!isset($to)   || $user_nbr<=99)   $to=date("Y-m-d");
                                                # Currencies
$currencies = array('USD','EUR','JPY','YUA','CHF',
                    'GBP','SEK','SGD','HKD','RUP',
                    'REA');

if (isset($refCurcy)) {                         # Reference currency
  $stoCur='t';
} else {
  $cmd = "SELECT ref_curcy,ref_rate FROM portfolios WHERE user_nbr=$user_nbr;";
  $ptfs=SQLquery($db,$cmd); $nptf=SQLnumrows($ptfs);
  if ($nptf>0) {
    $ptf=SQLobject($ptfs,0);
    $refCurcy=$ptf->ref_curcy; $refRate=$ptf->ref_rate;
  } else {
    $refCurcy="USD"; $refRate="0.02";
  }
}

                                                # ----- Portfolio
if (!isset($request) || strstr($request,"portfolio")) {

 if (isset($stoCur) && $user_nbr>99) {          # Store
   $cmd = "SELECT ref_curcy FROM portfolios WHERE user_nbr=$user_nbr;";
   $ptfs=SQLquery($db,$cmd); $nptf=SQLnumrows($ptfs);
   if ($nptf!=1) {
     $cmd="INSERT INTO portfolios (user_nbr,ref_curcy,ref_rate) ".
          "VALUES ($user_nbr,'$refCurcy','$refRate');";
   } else {
     $cmd="UPDATE portfolios SET ref_curcy='$refCurcy',ref_rate='$refRate' ".
          "WHERE user_nbr=$user_nbr;";
   }
   $r=SQLquery($db,$cmd);
 }
                                                # Portfolio request
 echo "<br>
 <form name=frmDropdowns action=portfolio.php method=post>
   <select name=request onChange=\"go();\">
     <option selected>portfolio
     <option>assets
     <option>currencies
   </select>
   reference currency
   <select name=refCurcy>
     <option selected>$refCurcy\n";

 for ($i=0; $i<count($currencies); $i++) {      # Portfolio currency
   echo "     <option>$currencies[$i]\n";
 }
                                                # Portfolio date,  submit
 echo "   </select>
   from <input type=text size=10 name=from value=\"".$from."\">
   to   <input type=text size=10 name=to value=\"".$to."\">
   <a href=\"http://www.bloomberg.com/\"> spot rate</a>:
   <input type=text size=4 name=refRate value=\"".$refRate."\">
   <input type=submit value=Submit>
 </form>";

} else if (strstr($request,"asset")) {        # ----- Asset

 if (strstr($request,"assets")) $request="asset list";

 if (isset($asset) && $asset!='' && $user_nbr>99) {

  if (strstr($request,"insert") && !isset($sel)) { #     SQL insert
    $cmd = "SELECT asset_nbr FROM assets ".
           "WHERE symb='$asset' AND user_nbr=$user_nbr;";
    $asss=SQLquery($db,$cmd); $nass=SQLnumrows($asss);
    if ($nass==0) {
      $cmd="INSERT INTO assets (user_nbr,symb,curcy,nbr,day,paid) ".
        "VALUES ($user_nbr,'$asset','$curcy','$nbr','$dat','$paid');";
      $r=SQLquery($db,$cmd);
      $request="asset edit"; $asset="";
    } else {
      echo "A position exists for $asset: update the existing values<br>";
      $request="asset edit"; $sel=0;
    }
  }
  if (isset($sel) && strstr($request,"delete")) {        # SQL delete
    $cmd = "DELETE FROM assets WHERE symb='$asset' AND user_nbr=$user_nbr;";
    $r=SQLquery($db,$cmd);
    $request="asset edit"; unset($sel);
  } else if (!isset($sel) && strstr($request,"edit")) {  # SQL update
    $cmd="UPDATE assets SET symb='$asset',curcy='$curcy',".
     "nbr='$nbr',day='$dat',paid='$paid'".
     " WHERE symb='$asset' AND user_nbr=$user_nbr;";
    $r=SQLquery($db,$cmd);
  } else if (isset($sel)) {                              # SQL select
    $cmd = "SELECT asset_nbr,symb,curcy,nbr,day,paid FROM assets ".
           "WHERE symb='$asset' AND user_nbr=$user_nbr;";
    $asss=SQLquery($db,$cmd); $nass=SQLnumrows($asss);
    $ass=SQLobject($asss,0);
    $asset=$ass->symb; $curcy=$ass->curcy;
    $nbr=$ass->nbr;    $paid=$ass->paid;  $dat=$ass->day;
  }
 }
 if ($asset=='' || strstr($request,"insert")) {          # Default
    $asset=""; $curcy="USD";
    $nbr=0;    $paid="10.00";  $dat=date("d-m-Y");
 }
                                              # Asset request
 echo "<br>
 <form name=frmDropdowns action=portfolio.php method=post>
   <select name=request onChange=\"go();\">
     <option selected>$request
     <option>asset insert
     <option>asset edit
     <option>asset delete
     <option>asset list
     <option>portfolio
   </select>";
                                              # Asset list selector
 if (!isset($sel) && !strstr($request,"insert")) {
   $cmd = "SELECT asset_nbr,symb,curcy,nbr,day,paid FROM assets ".
          "WHERE user_nbr=$user_nbr ORDER BY symb;";
   $asss=SQLquery($db,$cmd); $nass=SQLnumrows($asss);
   echo "   <input type=hidden name=sel value=0>
   <select name=asset>";
   $i=0; while ($i<$nass) { 
     $ass=SQLobject($asss,$i++);
     echo "     <option>$ass->symb\n"; 
   }
   echo "   </select>
   <input type=submit value=Submit><br><p>
   <table border=0 cellspacing=0 align=left><tr bgcolor=#bcbcbc>
   <th align=center>Ticker</th>
   <th align=center>Currency</th>
   <th align=center>Number</th>
   <th align=center>Date</th>
   <th align=center>Paid</th>
   <th align=center>Current</th>
   <th align=center>Edit</th>
   <th align=center>Del.</th></tr><tr>";
   for ($i=0; $i<$nass; $i++) {
    $ass=SQLobject($asss,$i);
    if ($i%2==1) echo "<tr bgcolor=#fcfcfc>";
    else              echo "<tr bgcolor=#dcdcdc>";
    echo "
      <td align=center><a href=\"http://finance.yahoo.com/q?s=$ass->symb&d=t\">$ass->symb</a></td>
      <td align=center>$ass->curcy</td>
      <td align=center>$ass->nbr</td>
      <td align=center>$ass->day</td>
      <td align=center>$ass->paid</td>
      <td align=center>NA</td>
      <td align=center><a href=\"portfolio.php?request=asset edit&asset=$ass->symb&sel=0\">E</a></td>
      <td align=center><a href=\"portfolio.php?request=asset delete&asset=$ass->symb&sel=0\">D</a></td></tr>";
   }
   echo "</table>";
 }
                                              # Asset insert
 if (isset($sel) || strstr($request,"insert")) {
   echo "   <input type=submit value=Submit><br><p>
   <table border=0 cellspacing=0 align=left><tr>
     <td><a href=\"http://finance.yahoo.com/l\">Symbol:</a>
       <input type=text size=8 name=asset value=\"".$asset."\"></td>
     <td>currency:<select name=curcy>
          <option selected>$refCurcy\n";
   for ($i=0; $i<count($currencies); $i++) {      # currencies
     echo "     <option>$currencies[$i]\n";
   }
   echo "         </select></td>
     <td>Nbr:
       <input type=text size=4 name=nbr value=\"".$nbr."\"></td>
     <td>Paid:
       <input type=text size=6 name=paid value=\"".$paid."\"></td>
     <td>Date:
       <input type=text size=10 name=dat value=\"".$dat."\"></td>
     </tr></table>";
 }
 echo "</form>";
}
                                                # ----- Analyse
$fromto=str_replace("-","",$from)."-".str_replace("-","",$to);
$a=substr($from,5,2); $b=substr($from,8,2); $c=substr($from,0,4);
$d=substr($to  ,5,2); $e=substr($to  ,8,2); $f=substr($to  ,0,4);
$downld_error="";

if (!isset($request) || strstr($request,"portfolio")) {
 $cmd = "SELECT asset_nbr,symb,curcy,nbr,day,paid FROM assets ".
        "WHERE user_nbr=$user_nbr ORDER BY symb;";
 $asss=SQLquery($db,$cmd); $nass=SQLnumrows($asss);
 $ip1=1;
 echo "<br clear=both><p>
  <applet codebase=\"../applet/PTF/\" code=PTFSolution.class width=780 height=300>\n ".
 " <param name=sym_0 value=\"forex\"> <param name=cur_0 value=\"$refCurcy\"> ".
 " <param name=wgt_0 value=\"0\"> ";
 if ($c<2000) echo
    " <param name=url_0 value=\"".$url."downld/quotes/currencies90.csv\">\n";
 else if ($c<2004) echo
    " <param name=url_0 value=\"".$url."downld/quotes/currencies00.csv\">\n";
 else echo
    " <param name=url_0 value=\"".$url."downld/quotes/currencies.csv\">\n";

 for($i=0; $i<$nass; $i++) {
   $ass=SQLobject($asss,$i);
   $file=$ass->symb."-".substr($c,2,2).$a.$b."-".substr($f,2,2).$d.$e.".csv";
   $URLfile= $url.$users."DATA/".$file;
   $DIRfile=$home.$users."DATA/".$file;
   if (file_exists($DIRfile)) {
     $stat=0;
   } else {                                             # download from yahoo
     $cmd = $wget." -O $DIRfile ".
        " 'http://table.finance.yahoo.com/table.csv?".
        "s=$ass->symb&d=$d&e=$e&f=$f&a=$a&b=$b&c=$c&g=d&ignore=.csv';".
        " chmod ugo+rw $DIRfile";
     system($cmd,$stat);
#    $cmd="nline=`cat $DIRfile | wc | awk '{ print \$1 }'`; ".
#         "if [ `expr \$nline > 2` ]; then EXIT=1; else; EXIT=0; fi;".
#         " exit \$EXIT";
     $cmd="cat $DIRfile | wc | awk '{ print \$1 }'";
     $nline=exec($cmd);
     if ($nline<3) {
       $cmd="rm -f $DIRfile";
       system($cmd,$stat);
       $stat=1;
     }
   }
   if ($stat) {
     if ($downld_error=="") 
     $downld_error="<blink><b>The following symbols are currently not ".
        "available and have been ignored:</b></blink> ";
     $downld_error=$downld_error."&nbsp; $ass->symb";
     $cmd="rm -f $DIRfile";
     system($cmd,$stat);
   } else {
     echo "  <param name=sym_$ip1 value=\"$ass->symb\">"; 
     echo "  <param name=cur_$ip1 value=\"$ass->curcy\">"; 
     echo "  <param name=wgt_$ip1 value=\"$ass->nbr\">"; 
     echo "  <param name=url_$ip1 value=\"$URLfile\">\n"; 
     $ip1=$ip1+1;
   }
  }
  echo "  <param name=nass value=\"$ip1\"><param name=rate  value=\"$refRate\"> 
  <param name=from value=\"$from\">   <param name=to value=\"$to\">
  <param name=bgColor value=DCDCDC>   <param name=dkColor value=FFF5EE>
  <param name=appletWidth value=780>  <param name=appletHeight value=300>
  <param name=canvasWidth value=550>  <param name=canvasHeight value=300>
  <param name=leftMargin value=80>    <param name=rightMargin value=40>
  <param name=bottomMargin value=40>  <param name=topMargin value=40>
  <param name=output value=\"1\">     <param name=exercise value=\"0.00\">
  </applet><br>$downld_error.<br>\n";
  echo "<a href=PTF_help_tag.php>PTFSolution applet:</a>
   Press <b>Draw</b> to display the daily closing price multiplied by the 
   exchange rate and the number of assets in any chosen reference currency.
   <b>Click</b> inside the plot area and check the browser status field 
   to visualize the trading date and measure a coordinate. <b>Print</b> 
   sends a number output to the <a href=../SRC/faq.php#7>java console</a>.
   You can <b>highlight</b> specific assets and <b>switch</b> between
   <i>Portfolio value</i> to plot the price history,
   <i>Compare assets</i> that are normalized to unity at the beginning,
   <i>Volatility [%]</i> to plot EWMA94 averages,
   <i>Correlation</i> to plot EWMA94 averages and print the correlation
      table at the end to the Java console,
   <i>Drift [%]</i> and <i>Sharpe ratio</i> to monitor the performance,
   <i>Foreign exchange</i> and <i>CompareCurrency</i> to display the 
   evolution of the foreign exchange rates. To facilitate the reading, 
   Foreign Exchange rates here are given for the price of 100 JPN, 100 RUP, 
   10 YUA, 10 SEK, 10 HKD and all others for the price of 1 single currency 
   unit bought that day in the chosen reference currency.";
}

?>
<br><p>
<?php myfooter($user_nbr,'..',$myPermit); ?>
