Displaying the value of a stock portfolioDisplaying postsDisplaying subcategories of subcategoriesTwo while for the same queryFunction to rebalance portfolioPHP rating function for getting the average value of columnGetting the last post of all threadsCalculate stock portfolio profit based on CSV dataDisplaying comments and replies retrieved from a databaseSimple cryptocurrency portfolio rebalancerDisplaying topics in a PHP forum

How could a planet have erratic days?

A Trivial Diagnosis

Short story about a deaf man, who cuts people tongues

How can I write humor as character trait?

Why do Radio Buttons not fill the entire outer circle?

What is the highest possible scrabble score for placing a single tile

How to make money from a browser who sees 5 seconds into the future of any web page?

What are some good ways to treat frozen vegetables such that they behave like fresh vegetables when stir frying them?

Does an advisor owe his/her student anything? Will an advisor keep a PhD student only out of pity?

Why does AES have exactly 10 rounds for a 128-bit key, 12 for 192 bits and 14 for a 256-bit key size?

Will number of steps recorded on FitBit/any fitness tracker add up distance in PokemonGo?

Is it allowed to activate the ability of multiple planeswalkers in a single turn?

How do I fix the group tension caused by my character stealing and possibly killing without provocation?

Strong empirical falsification of quantum mechanics based on vacuum energy density?

Why should universal income be universal?

How can ping know if my host is down

Make a Bowl of Alphabet Soup

Delete multiple columns using awk or sed

How to draw a matrix with arrows in limited space

Multiplicative persistence

Is this toilet slogan correct usage of the English language?

awk assign to multiple variables at once

"It doesn't matter" or "it won't matter"?

What features enable the Su-25 Frogfoot to operate with such a wide variety of fuels?



Displaying the value of a stock portfolio


Displaying postsDisplaying subcategories of subcategoriesTwo while for the same queryFunction to rebalance portfolioPHP rating function for getting the average value of columnGetting the last post of all threadsCalculate stock portfolio profit based on CSV dataDisplaying comments and replies retrieved from a databaseSimple cryptocurrency portfolio rebalancerDisplaying topics in a PHP forum













0












$begingroup$


Some people have mentioned to me that my site is quite inefficient and given that it's taking ~17secs to load now, I'd like to change that but I've no idea how. I've tried Gzip to compress it but it didn't help. I got rid of some double quotes (I.e. "") and have used single quotes (I.e. '') instead, as well as got rid of some HTML blank spaces but that's about it.



Here is most of my code, excluding some JS to save space. Either way, when I open the Google Chrome developer console on my site, it shows that it's the PHP file itself that takes so long to load, not JS so that's why I'm just showing that below. It's just this one page that's loading slowly, all others sites are very quick. I'd love some tips on how to make this more efficient.



<?php
require('includes/connection.php');
require('includes/config.php');
// Page name
$title = 'Portfolio';
// Include the header template
require('layout/header.php');

// If for some reason, not logged in then redirect to login page
if(!$user->is_logged_in()) header('Location: login.php'); exit();
?>
<div>
<h2><?php echo htmlspecialchars($_SESSION['username'], ENT_QUOTES); ?></h2>
<button id="opener" class='btn btn-success' >Advanced Company Data</button>
<div id="dialog" title="Advanced Company Data"><a href="http://www.nasdaq.com/symbol/aapl">Exchange Information</a>
</div>
</div>
<script>
$("#dialog").dialog(
autoOpen: false
);
$("#opener").click(function()
$("#dialog").dialog("open", "modal", true );
);
</script>
</div>
<?php
$spy = file_get_contents('https://api.iextrading.com/1.0/stock/spy/stats/year1ChangePercent');
$spy = json_decode($spy,TRUE);
// Initialising variables to store extracted information
$name = [];
$symbol = [];
$open = [];
$close = [];
$high = [];
$low = [];
$lastprice = [];
$y = 0;
$z = '';
$key = '93dcc722279c3a7577f248b09ef6167f';

// Retreiving information from database
$memberid = $_SESSION['memberID'];
$sql = "SELECT * FROM portfolio WHERE memberID = $memberid";
$result = mysqli_query($conn, $sql);

// Check if databse is empty
if (mysqli_num_rows($result) > 0)

while($row = mysqli_fetch_assoc($result))

$sym[$y] = $row['stocks_symbol'];
$pri[$y] = $row['price'];
$vol[$y] = $row['quantity'];
$id[$y] = $row['memberid'];
$y += 1;


// If database empty
else

echo 'Portfolio Empty';
die();

mysqli_close($conn);

// Adding all stock names in one variable to enable API call
for($a=0;$a<$y;$a++)

$z = $z.$sym[$a].',';

$z = rtrim($z,',');

// API call
$contents = file_get_contents("http://marketdata.websol.barchart.com/getQuote.json?key=$key&symbols=$z&mode=R");
$contents = json_decode($contents, true);
// Check successfull API call
if($contents['status']['code'] == 200)

foreach($contents['results'] as $result)

array_push($name,$result['name']);
array_push($symbol,$result['symbol']);
array_push($open,$result['open']);
array_push($close,$result['close']);
array_push($high,$result['high']);
array_push($low,$result['low']);
array_push($lastprice,$result['lastPrice']);


// If API call unsuccessful
else

echo 'Error retreiving data. Please try again later.';
die();

?>
<!-- Generating Output in tabular format -->
<table id= test class='table table-responsive'>
<tr class='head warning'>
<th>Name</th>
<th>Symbol</th>
<th>Open</th>
<th>Close</th>
<th>High</th>
<th>Low</th>
<th>Last Price</th>
<th>Price Bought</th>
<th>Quantity</th>
<th>Change Per Stock</th>
<th>Profit/Loss</th>
<th>Amount Invested</th>
<th>Current Market Value</th>
<th>Dividend</th>
<th>Total Dividend</th>
<th>Company Description</th>
<th>Latest News</th>
</tr>
<?php
$profitOrLossSum = 0;
$dividendRateSum = 0;
$startEqSum = 0;
$sumOf = array();
$pnl = array();

for($x=0;$x<$y;$x++)
?>
<tr>
<td class="input"><?php echo $name[$x]; ?></td>
<td class="input"><?php echo $symbol[$x]; ?></td>
<td class="input"><?php echo $open[$x]; ?></td>
<td class="input"><?php echo $close[$x]; ?></td>
<td class="input"><?php echo $high[$x]; ?></td>
<td class="input"><?php echo $low[$x]; ?></td>
<td class="input"><?php echo $lastprice[$x]; ?></td>
<td class="input"><?php echo $pri[$x]; ?></td>
<td class="input"><?php echo $vol[$x]; ?></td>
<td class="input"><?php
if($pri[$x] > $lastprice[$x])

echo $lastprice[$x]-$pri[$x];

else if($pri[$x] < $lastprice[$x])

echo $lastprice[$x]-$pri[$x];

else
echo '0';
?></td>
<td class="input"><b><?php
$profitOrLoss = ($lastprice[$x]-$pri[$x]) * $vol[$x];
$profitOrLossSum += $profitOrLoss;
$pnl[] = $profitOrLoss;
echo $profitOrLoss;
?></b></td>
<td><?php
$starteq = $pri[$x] * $vol[$x];
$startEqSum += $starteq;
echo $starteq;
?></td>
<td><b><?php
$firstno1 = floatval($vol[$x]);
$secondno1 = floatval($lastprice[$x]);
$sumOf[] = $firstno1 * $secondno1;
$sum1 = $firstno1 * $secondno1;
echo ($sum1);
?>
</b></td>
<td><?php
$div = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=stats&filter=dividendRate");
$div = json_decode($div,TRUE);
$sum = 0;
foreach($div as $divi => $value)
echo $value['stats']['dividendRate'];
$sum += (floatval($vol[$x]) + floatval($value['stats']['dividendRate']));

?></td>
<td><?php
$firstno = floatval($vol[$x]);
$secondno = floatval($value['stats']['dividendRate']);
$sum2 = 0;
$sum2 += $firstno * $secondno;
echo ($sum2);
$dividendRateSum += $sum2;
?></td>
<td class="input"><?php
$desc = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=company&filter=description");
$desc = json_decode($desc,TRUE);
foreach($desc as $desc => $des)
echo $des['company']['description'];

?></td>
<td><?php
$desc1 = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=news&filter=headline,url&range=1m&last=1");
$desc1 = json_decode($desc1,TRUE);
foreach($desc1 as $key111 => $des1)
echo implode(PHP_EOL, array_column($des1['news'],'headline'));
?><br><?php $link = implode(PHP_EOL, array_column($des1['news'],'url'));
echo '<a href="'.$link.'">Link</a>';

?></td>
</tr>
<?php

$arr = array('profitOrLossSum' => $profitOrLossSum, 'dividendRateSum' => $dividendRateSum);
$arr1 = array('startEqSum' => $startEqSum);
$array = array_combine($name, $sumOf);
$array10 = array_combine($name, $pnl);
?>
</table>

<h3> SPY %YTD= <?php echo $spy1 = number_format($spy *100, 2); ?>%</h3>
<br>
<h3> Starting Equity= $<?php echo $startEqSum; ?></h3>
<h3> Current Equity= $<?php echo $profitOrLossSum; ?></h3>
<h3> Total Profit= $<?php echo $profitOrLossSum - $startEqSum; ?></h3>
<h3> % Gain/Loss= <?php echo $gain = number_format((($profitOrLossSum - $startEqSum) / $startEqSum) * 100, 2); ?>%</h3>
<h3> Total Dividend= $<?php echo $dividendRateSum / 4; ?>/Quarter</h3>
<h3> Portfolio vs SPY= <?php echo $gain-$spy1; ?>%</h3><br>
</body>









share|improve this question











$endgroup$




bumped to the homepage by Community 6 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.



















    0












    $begingroup$


    Some people have mentioned to me that my site is quite inefficient and given that it's taking ~17secs to load now, I'd like to change that but I've no idea how. I've tried Gzip to compress it but it didn't help. I got rid of some double quotes (I.e. "") and have used single quotes (I.e. '') instead, as well as got rid of some HTML blank spaces but that's about it.



    Here is most of my code, excluding some JS to save space. Either way, when I open the Google Chrome developer console on my site, it shows that it's the PHP file itself that takes so long to load, not JS so that's why I'm just showing that below. It's just this one page that's loading slowly, all others sites are very quick. I'd love some tips on how to make this more efficient.



    <?php
    require('includes/connection.php');
    require('includes/config.php');
    // Page name
    $title = 'Portfolio';
    // Include the header template
    require('layout/header.php');

    // If for some reason, not logged in then redirect to login page
    if(!$user->is_logged_in()) header('Location: login.php'); exit();
    ?>
    <div>
    <h2><?php echo htmlspecialchars($_SESSION['username'], ENT_QUOTES); ?></h2>
    <button id="opener" class='btn btn-success' >Advanced Company Data</button>
    <div id="dialog" title="Advanced Company Data"><a href="http://www.nasdaq.com/symbol/aapl">Exchange Information</a>
    </div>
    </div>
    <script>
    $("#dialog").dialog(
    autoOpen: false
    );
    $("#opener").click(function()
    $("#dialog").dialog("open", "modal", true );
    );
    </script>
    </div>
    <?php
    $spy = file_get_contents('https://api.iextrading.com/1.0/stock/spy/stats/year1ChangePercent');
    $spy = json_decode($spy,TRUE);
    // Initialising variables to store extracted information
    $name = [];
    $symbol = [];
    $open = [];
    $close = [];
    $high = [];
    $low = [];
    $lastprice = [];
    $y = 0;
    $z = '';
    $key = '93dcc722279c3a7577f248b09ef6167f';

    // Retreiving information from database
    $memberid = $_SESSION['memberID'];
    $sql = "SELECT * FROM portfolio WHERE memberID = $memberid";
    $result = mysqli_query($conn, $sql);

    // Check if databse is empty
    if (mysqli_num_rows($result) > 0)

    while($row = mysqli_fetch_assoc($result))

    $sym[$y] = $row['stocks_symbol'];
    $pri[$y] = $row['price'];
    $vol[$y] = $row['quantity'];
    $id[$y] = $row['memberid'];
    $y += 1;


    // If database empty
    else

    echo 'Portfolio Empty';
    die();

    mysqli_close($conn);

    // Adding all stock names in one variable to enable API call
    for($a=0;$a<$y;$a++)

    $z = $z.$sym[$a].',';

    $z = rtrim($z,',');

    // API call
    $contents = file_get_contents("http://marketdata.websol.barchart.com/getQuote.json?key=$key&symbols=$z&mode=R");
    $contents = json_decode($contents, true);
    // Check successfull API call
    if($contents['status']['code'] == 200)

    foreach($contents['results'] as $result)

    array_push($name,$result['name']);
    array_push($symbol,$result['symbol']);
    array_push($open,$result['open']);
    array_push($close,$result['close']);
    array_push($high,$result['high']);
    array_push($low,$result['low']);
    array_push($lastprice,$result['lastPrice']);


    // If API call unsuccessful
    else

    echo 'Error retreiving data. Please try again later.';
    die();

    ?>
    <!-- Generating Output in tabular format -->
    <table id= test class='table table-responsive'>
    <tr class='head warning'>
    <th>Name</th>
    <th>Symbol</th>
    <th>Open</th>
    <th>Close</th>
    <th>High</th>
    <th>Low</th>
    <th>Last Price</th>
    <th>Price Bought</th>
    <th>Quantity</th>
    <th>Change Per Stock</th>
    <th>Profit/Loss</th>
    <th>Amount Invested</th>
    <th>Current Market Value</th>
    <th>Dividend</th>
    <th>Total Dividend</th>
    <th>Company Description</th>
    <th>Latest News</th>
    </tr>
    <?php
    $profitOrLossSum = 0;
    $dividendRateSum = 0;
    $startEqSum = 0;
    $sumOf = array();
    $pnl = array();

    for($x=0;$x<$y;$x++)
    ?>
    <tr>
    <td class="input"><?php echo $name[$x]; ?></td>
    <td class="input"><?php echo $symbol[$x]; ?></td>
    <td class="input"><?php echo $open[$x]; ?></td>
    <td class="input"><?php echo $close[$x]; ?></td>
    <td class="input"><?php echo $high[$x]; ?></td>
    <td class="input"><?php echo $low[$x]; ?></td>
    <td class="input"><?php echo $lastprice[$x]; ?></td>
    <td class="input"><?php echo $pri[$x]; ?></td>
    <td class="input"><?php echo $vol[$x]; ?></td>
    <td class="input"><?php
    if($pri[$x] > $lastprice[$x])

    echo $lastprice[$x]-$pri[$x];

    else if($pri[$x] < $lastprice[$x])

    echo $lastprice[$x]-$pri[$x];

    else
    echo '0';
    ?></td>
    <td class="input"><b><?php
    $profitOrLoss = ($lastprice[$x]-$pri[$x]) * $vol[$x];
    $profitOrLossSum += $profitOrLoss;
    $pnl[] = $profitOrLoss;
    echo $profitOrLoss;
    ?></b></td>
    <td><?php
    $starteq = $pri[$x] * $vol[$x];
    $startEqSum += $starteq;
    echo $starteq;
    ?></td>
    <td><b><?php
    $firstno1 = floatval($vol[$x]);
    $secondno1 = floatval($lastprice[$x]);
    $sumOf[] = $firstno1 * $secondno1;
    $sum1 = $firstno1 * $secondno1;
    echo ($sum1);
    ?>
    </b></td>
    <td><?php
    $div = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=stats&filter=dividendRate");
    $div = json_decode($div,TRUE);
    $sum = 0;
    foreach($div as $divi => $value)
    echo $value['stats']['dividendRate'];
    $sum += (floatval($vol[$x]) + floatval($value['stats']['dividendRate']));

    ?></td>
    <td><?php
    $firstno = floatval($vol[$x]);
    $secondno = floatval($value['stats']['dividendRate']);
    $sum2 = 0;
    $sum2 += $firstno * $secondno;
    echo ($sum2);
    $dividendRateSum += $sum2;
    ?></td>
    <td class="input"><?php
    $desc = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=company&filter=description");
    $desc = json_decode($desc,TRUE);
    foreach($desc as $desc => $des)
    echo $des['company']['description'];

    ?></td>
    <td><?php
    $desc1 = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=news&filter=headline,url&range=1m&last=1");
    $desc1 = json_decode($desc1,TRUE);
    foreach($desc1 as $key111 => $des1)
    echo implode(PHP_EOL, array_column($des1['news'],'headline'));
    ?><br><?php $link = implode(PHP_EOL, array_column($des1['news'],'url'));
    echo '<a href="'.$link.'">Link</a>';

    ?></td>
    </tr>
    <?php

    $arr = array('profitOrLossSum' => $profitOrLossSum, 'dividendRateSum' => $dividendRateSum);
    $arr1 = array('startEqSum' => $startEqSum);
    $array = array_combine($name, $sumOf);
    $array10 = array_combine($name, $pnl);
    ?>
    </table>

    <h3> SPY %YTD= <?php echo $spy1 = number_format($spy *100, 2); ?>%</h3>
    <br>
    <h3> Starting Equity= $<?php echo $startEqSum; ?></h3>
    <h3> Current Equity= $<?php echo $profitOrLossSum; ?></h3>
    <h3> Total Profit= $<?php echo $profitOrLossSum - $startEqSum; ?></h3>
    <h3> % Gain/Loss= <?php echo $gain = number_format((($profitOrLossSum - $startEqSum) / $startEqSum) * 100, 2); ?>%</h3>
    <h3> Total Dividend= $<?php echo $dividendRateSum / 4; ?>/Quarter</h3>
    <h3> Portfolio vs SPY= <?php echo $gain-$spy1; ?>%</h3><br>
    </body>









    share|improve this question











    $endgroup$




    bumped to the homepage by Community 6 mins ago


    This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.

















      0












      0








      0





      $begingroup$


      Some people have mentioned to me that my site is quite inefficient and given that it's taking ~17secs to load now, I'd like to change that but I've no idea how. I've tried Gzip to compress it but it didn't help. I got rid of some double quotes (I.e. "") and have used single quotes (I.e. '') instead, as well as got rid of some HTML blank spaces but that's about it.



      Here is most of my code, excluding some JS to save space. Either way, when I open the Google Chrome developer console on my site, it shows that it's the PHP file itself that takes so long to load, not JS so that's why I'm just showing that below. It's just this one page that's loading slowly, all others sites are very quick. I'd love some tips on how to make this more efficient.



      <?php
      require('includes/connection.php');
      require('includes/config.php');
      // Page name
      $title = 'Portfolio';
      // Include the header template
      require('layout/header.php');

      // If for some reason, not logged in then redirect to login page
      if(!$user->is_logged_in()) header('Location: login.php'); exit();
      ?>
      <div>
      <h2><?php echo htmlspecialchars($_SESSION['username'], ENT_QUOTES); ?></h2>
      <button id="opener" class='btn btn-success' >Advanced Company Data</button>
      <div id="dialog" title="Advanced Company Data"><a href="http://www.nasdaq.com/symbol/aapl">Exchange Information</a>
      </div>
      </div>
      <script>
      $("#dialog").dialog(
      autoOpen: false
      );
      $("#opener").click(function()
      $("#dialog").dialog("open", "modal", true );
      );
      </script>
      </div>
      <?php
      $spy = file_get_contents('https://api.iextrading.com/1.0/stock/spy/stats/year1ChangePercent');
      $spy = json_decode($spy,TRUE);
      // Initialising variables to store extracted information
      $name = [];
      $symbol = [];
      $open = [];
      $close = [];
      $high = [];
      $low = [];
      $lastprice = [];
      $y = 0;
      $z = '';
      $key = '93dcc722279c3a7577f248b09ef6167f';

      // Retreiving information from database
      $memberid = $_SESSION['memberID'];
      $sql = "SELECT * FROM portfolio WHERE memberID = $memberid";
      $result = mysqli_query($conn, $sql);

      // Check if databse is empty
      if (mysqli_num_rows($result) > 0)

      while($row = mysqli_fetch_assoc($result))

      $sym[$y] = $row['stocks_symbol'];
      $pri[$y] = $row['price'];
      $vol[$y] = $row['quantity'];
      $id[$y] = $row['memberid'];
      $y += 1;


      // If database empty
      else

      echo 'Portfolio Empty';
      die();

      mysqli_close($conn);

      // Adding all stock names in one variable to enable API call
      for($a=0;$a<$y;$a++)

      $z = $z.$sym[$a].',';

      $z = rtrim($z,',');

      // API call
      $contents = file_get_contents("http://marketdata.websol.barchart.com/getQuote.json?key=$key&symbols=$z&mode=R");
      $contents = json_decode($contents, true);
      // Check successfull API call
      if($contents['status']['code'] == 200)

      foreach($contents['results'] as $result)

      array_push($name,$result['name']);
      array_push($symbol,$result['symbol']);
      array_push($open,$result['open']);
      array_push($close,$result['close']);
      array_push($high,$result['high']);
      array_push($low,$result['low']);
      array_push($lastprice,$result['lastPrice']);


      // If API call unsuccessful
      else

      echo 'Error retreiving data. Please try again later.';
      die();

      ?>
      <!-- Generating Output in tabular format -->
      <table id= test class='table table-responsive'>
      <tr class='head warning'>
      <th>Name</th>
      <th>Symbol</th>
      <th>Open</th>
      <th>Close</th>
      <th>High</th>
      <th>Low</th>
      <th>Last Price</th>
      <th>Price Bought</th>
      <th>Quantity</th>
      <th>Change Per Stock</th>
      <th>Profit/Loss</th>
      <th>Amount Invested</th>
      <th>Current Market Value</th>
      <th>Dividend</th>
      <th>Total Dividend</th>
      <th>Company Description</th>
      <th>Latest News</th>
      </tr>
      <?php
      $profitOrLossSum = 0;
      $dividendRateSum = 0;
      $startEqSum = 0;
      $sumOf = array();
      $pnl = array();

      for($x=0;$x<$y;$x++)
      ?>
      <tr>
      <td class="input"><?php echo $name[$x]; ?></td>
      <td class="input"><?php echo $symbol[$x]; ?></td>
      <td class="input"><?php echo $open[$x]; ?></td>
      <td class="input"><?php echo $close[$x]; ?></td>
      <td class="input"><?php echo $high[$x]; ?></td>
      <td class="input"><?php echo $low[$x]; ?></td>
      <td class="input"><?php echo $lastprice[$x]; ?></td>
      <td class="input"><?php echo $pri[$x]; ?></td>
      <td class="input"><?php echo $vol[$x]; ?></td>
      <td class="input"><?php
      if($pri[$x] > $lastprice[$x])

      echo $lastprice[$x]-$pri[$x];

      else if($pri[$x] < $lastprice[$x])

      echo $lastprice[$x]-$pri[$x];

      else
      echo '0';
      ?></td>
      <td class="input"><b><?php
      $profitOrLoss = ($lastprice[$x]-$pri[$x]) * $vol[$x];
      $profitOrLossSum += $profitOrLoss;
      $pnl[] = $profitOrLoss;
      echo $profitOrLoss;
      ?></b></td>
      <td><?php
      $starteq = $pri[$x] * $vol[$x];
      $startEqSum += $starteq;
      echo $starteq;
      ?></td>
      <td><b><?php
      $firstno1 = floatval($vol[$x]);
      $secondno1 = floatval($lastprice[$x]);
      $sumOf[] = $firstno1 * $secondno1;
      $sum1 = $firstno1 * $secondno1;
      echo ($sum1);
      ?>
      </b></td>
      <td><?php
      $div = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=stats&filter=dividendRate");
      $div = json_decode($div,TRUE);
      $sum = 0;
      foreach($div as $divi => $value)
      echo $value['stats']['dividendRate'];
      $sum += (floatval($vol[$x]) + floatval($value['stats']['dividendRate']));

      ?></td>
      <td><?php
      $firstno = floatval($vol[$x]);
      $secondno = floatval($value['stats']['dividendRate']);
      $sum2 = 0;
      $sum2 += $firstno * $secondno;
      echo ($sum2);
      $dividendRateSum += $sum2;
      ?></td>
      <td class="input"><?php
      $desc = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=company&filter=description");
      $desc = json_decode($desc,TRUE);
      foreach($desc as $desc => $des)
      echo $des['company']['description'];

      ?></td>
      <td><?php
      $desc1 = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=news&filter=headline,url&range=1m&last=1");
      $desc1 = json_decode($desc1,TRUE);
      foreach($desc1 as $key111 => $des1)
      echo implode(PHP_EOL, array_column($des1['news'],'headline'));
      ?><br><?php $link = implode(PHP_EOL, array_column($des1['news'],'url'));
      echo '<a href="'.$link.'">Link</a>';

      ?></td>
      </tr>
      <?php

      $arr = array('profitOrLossSum' => $profitOrLossSum, 'dividendRateSum' => $dividendRateSum);
      $arr1 = array('startEqSum' => $startEqSum);
      $array = array_combine($name, $sumOf);
      $array10 = array_combine($name, $pnl);
      ?>
      </table>

      <h3> SPY %YTD= <?php echo $spy1 = number_format($spy *100, 2); ?>%</h3>
      <br>
      <h3> Starting Equity= $<?php echo $startEqSum; ?></h3>
      <h3> Current Equity= $<?php echo $profitOrLossSum; ?></h3>
      <h3> Total Profit= $<?php echo $profitOrLossSum - $startEqSum; ?></h3>
      <h3> % Gain/Loss= <?php echo $gain = number_format((($profitOrLossSum - $startEqSum) / $startEqSum) * 100, 2); ?>%</h3>
      <h3> Total Dividend= $<?php echo $dividendRateSum / 4; ?>/Quarter</h3>
      <h3> Portfolio vs SPY= <?php echo $gain-$spy1; ?>%</h3><br>
      </body>









      share|improve this question











      $endgroup$




      Some people have mentioned to me that my site is quite inefficient and given that it's taking ~17secs to load now, I'd like to change that but I've no idea how. I've tried Gzip to compress it but it didn't help. I got rid of some double quotes (I.e. "") and have used single quotes (I.e. '') instead, as well as got rid of some HTML blank spaces but that's about it.



      Here is most of my code, excluding some JS to save space. Either way, when I open the Google Chrome developer console on my site, it shows that it's the PHP file itself that takes so long to load, not JS so that's why I'm just showing that below. It's just this one page that's loading slowly, all others sites are very quick. I'd love some tips on how to make this more efficient.



      <?php
      require('includes/connection.php');
      require('includes/config.php');
      // Page name
      $title = 'Portfolio';
      // Include the header template
      require('layout/header.php');

      // If for some reason, not logged in then redirect to login page
      if(!$user->is_logged_in()) header('Location: login.php'); exit();
      ?>
      <div>
      <h2><?php echo htmlspecialchars($_SESSION['username'], ENT_QUOTES); ?></h2>
      <button id="opener" class='btn btn-success' >Advanced Company Data</button>
      <div id="dialog" title="Advanced Company Data"><a href="http://www.nasdaq.com/symbol/aapl">Exchange Information</a>
      </div>
      </div>
      <script>
      $("#dialog").dialog(
      autoOpen: false
      );
      $("#opener").click(function()
      $("#dialog").dialog("open", "modal", true );
      );
      </script>
      </div>
      <?php
      $spy = file_get_contents('https://api.iextrading.com/1.0/stock/spy/stats/year1ChangePercent');
      $spy = json_decode($spy,TRUE);
      // Initialising variables to store extracted information
      $name = [];
      $symbol = [];
      $open = [];
      $close = [];
      $high = [];
      $low = [];
      $lastprice = [];
      $y = 0;
      $z = '';
      $key = '93dcc722279c3a7577f248b09ef6167f';

      // Retreiving information from database
      $memberid = $_SESSION['memberID'];
      $sql = "SELECT * FROM portfolio WHERE memberID = $memberid";
      $result = mysqli_query($conn, $sql);

      // Check if databse is empty
      if (mysqli_num_rows($result) > 0)

      while($row = mysqli_fetch_assoc($result))

      $sym[$y] = $row['stocks_symbol'];
      $pri[$y] = $row['price'];
      $vol[$y] = $row['quantity'];
      $id[$y] = $row['memberid'];
      $y += 1;


      // If database empty
      else

      echo 'Portfolio Empty';
      die();

      mysqli_close($conn);

      // Adding all stock names in one variable to enable API call
      for($a=0;$a<$y;$a++)

      $z = $z.$sym[$a].',';

      $z = rtrim($z,',');

      // API call
      $contents = file_get_contents("http://marketdata.websol.barchart.com/getQuote.json?key=$key&symbols=$z&mode=R");
      $contents = json_decode($contents, true);
      // Check successfull API call
      if($contents['status']['code'] == 200)

      foreach($contents['results'] as $result)

      array_push($name,$result['name']);
      array_push($symbol,$result['symbol']);
      array_push($open,$result['open']);
      array_push($close,$result['close']);
      array_push($high,$result['high']);
      array_push($low,$result['low']);
      array_push($lastprice,$result['lastPrice']);


      // If API call unsuccessful
      else

      echo 'Error retreiving data. Please try again later.';
      die();

      ?>
      <!-- Generating Output in tabular format -->
      <table id= test class='table table-responsive'>
      <tr class='head warning'>
      <th>Name</th>
      <th>Symbol</th>
      <th>Open</th>
      <th>Close</th>
      <th>High</th>
      <th>Low</th>
      <th>Last Price</th>
      <th>Price Bought</th>
      <th>Quantity</th>
      <th>Change Per Stock</th>
      <th>Profit/Loss</th>
      <th>Amount Invested</th>
      <th>Current Market Value</th>
      <th>Dividend</th>
      <th>Total Dividend</th>
      <th>Company Description</th>
      <th>Latest News</th>
      </tr>
      <?php
      $profitOrLossSum = 0;
      $dividendRateSum = 0;
      $startEqSum = 0;
      $sumOf = array();
      $pnl = array();

      for($x=0;$x<$y;$x++)
      ?>
      <tr>
      <td class="input"><?php echo $name[$x]; ?></td>
      <td class="input"><?php echo $symbol[$x]; ?></td>
      <td class="input"><?php echo $open[$x]; ?></td>
      <td class="input"><?php echo $close[$x]; ?></td>
      <td class="input"><?php echo $high[$x]; ?></td>
      <td class="input"><?php echo $low[$x]; ?></td>
      <td class="input"><?php echo $lastprice[$x]; ?></td>
      <td class="input"><?php echo $pri[$x]; ?></td>
      <td class="input"><?php echo $vol[$x]; ?></td>
      <td class="input"><?php
      if($pri[$x] > $lastprice[$x])

      echo $lastprice[$x]-$pri[$x];

      else if($pri[$x] < $lastprice[$x])

      echo $lastprice[$x]-$pri[$x];

      else
      echo '0';
      ?></td>
      <td class="input"><b><?php
      $profitOrLoss = ($lastprice[$x]-$pri[$x]) * $vol[$x];
      $profitOrLossSum += $profitOrLoss;
      $pnl[] = $profitOrLoss;
      echo $profitOrLoss;
      ?></b></td>
      <td><?php
      $starteq = $pri[$x] * $vol[$x];
      $startEqSum += $starteq;
      echo $starteq;
      ?></td>
      <td><b><?php
      $firstno1 = floatval($vol[$x]);
      $secondno1 = floatval($lastprice[$x]);
      $sumOf[] = $firstno1 * $secondno1;
      $sum1 = $firstno1 * $secondno1;
      echo ($sum1);
      ?>
      </b></td>
      <td><?php
      $div = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=stats&filter=dividendRate");
      $div = json_decode($div,TRUE);
      $sum = 0;
      foreach($div as $divi => $value)
      echo $value['stats']['dividendRate'];
      $sum += (floatval($vol[$x]) + floatval($value['stats']['dividendRate']));

      ?></td>
      <td><?php
      $firstno = floatval($vol[$x]);
      $secondno = floatval($value['stats']['dividendRate']);
      $sum2 = 0;
      $sum2 += $firstno * $secondno;
      echo ($sum2);
      $dividendRateSum += $sum2;
      ?></td>
      <td class="input"><?php
      $desc = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=company&filter=description");
      $desc = json_decode($desc,TRUE);
      foreach($desc as $desc => $des)
      echo $des['company']['description'];

      ?></td>
      <td><?php
      $desc1 = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=news&filter=headline,url&range=1m&last=1");
      $desc1 = json_decode($desc1,TRUE);
      foreach($desc1 as $key111 => $des1)
      echo implode(PHP_EOL, array_column($des1['news'],'headline'));
      ?><br><?php $link = implode(PHP_EOL, array_column($des1['news'],'url'));
      echo '<a href="'.$link.'">Link</a>';

      ?></td>
      </tr>
      <?php

      $arr = array('profitOrLossSum' => $profitOrLossSum, 'dividendRateSum' => $dividendRateSum);
      $arr1 = array('startEqSum' => $startEqSum);
      $array = array_combine($name, $sumOf);
      $array10 = array_combine($name, $pnl);
      ?>
      </table>

      <h3> SPY %YTD= <?php echo $spy1 = number_format($spy *100, 2); ?>%</h3>
      <br>
      <h3> Starting Equity= $<?php echo $startEqSum; ?></h3>
      <h3> Current Equity= $<?php echo $profitOrLossSum; ?></h3>
      <h3> Total Profit= $<?php echo $profitOrLossSum - $startEqSum; ?></h3>
      <h3> % Gain/Loss= <?php echo $gain = number_format((($profitOrLossSum - $startEqSum) / $startEqSum) * 100, 2); ?>%</h3>
      <h3> Total Dividend= $<?php echo $dividendRateSum / 4; ?>/Quarter</h3>
      <h3> Portfolio vs SPY= <?php echo $gain-$spy1; ?>%</h3><br>
      </body>






      performance php sql api mysqli






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Feb 19 '18 at 4:06









      Sᴀᴍ Onᴇᴌᴀ

      9,88162165




      9,88162165










      asked Feb 18 '18 at 16:01









      FrenzyyFrenzyy

      6




      6





      bumped to the homepage by Community 6 mins ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







      bumped to the homepage by Community 6 mins ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.






















          1 Answer
          1






          active

          oldest

          votes


















          0












          $begingroup$

          You should copy your page and write the time taken for all file-get-content and for the query. So you ll know where come that it s very slow.
          How many people are using it? How many people are using your server? If too many it s saturated and very very slow : change your server or the internet connection or optimise your code.
          Next use echo to write text it s faster than stoping the script and coming back.
          Better to redo a sql query instead of downloading a file. You could also cache the most used queries eventually in a new database table.
          If using the script tag you should always inform what is the language.
          If you use only once a session variable, it s faster not to save it first in a variable.
          If you just need to display a value only don t save it in an array first but at the moment of running the query.
          Prefer to use variable instead of array it s faster.






          share|improve this answer









          $endgroup$












            Your Answer





            StackExchange.ifUsing("editor", function ()
            return StackExchange.using("mathjaxEditing", function ()
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            );
            );
            , "mathjax-editing");

            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "196"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f187809%2fdisplaying-the-value-of-a-stock-portfolio%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0












            $begingroup$

            You should copy your page and write the time taken for all file-get-content and for the query. So you ll know where come that it s very slow.
            How many people are using it? How many people are using your server? If too many it s saturated and very very slow : change your server or the internet connection or optimise your code.
            Next use echo to write text it s faster than stoping the script and coming back.
            Better to redo a sql query instead of downloading a file. You could also cache the most used queries eventually in a new database table.
            If using the script tag you should always inform what is the language.
            If you use only once a session variable, it s faster not to save it first in a variable.
            If you just need to display a value only don t save it in an array first but at the moment of running the query.
            Prefer to use variable instead of array it s faster.






            share|improve this answer









            $endgroup$

















              0












              $begingroup$

              You should copy your page and write the time taken for all file-get-content and for the query. So you ll know where come that it s very slow.
              How many people are using it? How many people are using your server? If too many it s saturated and very very slow : change your server or the internet connection or optimise your code.
              Next use echo to write text it s faster than stoping the script and coming back.
              Better to redo a sql query instead of downloading a file. You could also cache the most used queries eventually in a new database table.
              If using the script tag you should always inform what is the language.
              If you use only once a session variable, it s faster not to save it first in a variable.
              If you just need to display a value only don t save it in an array first but at the moment of running the query.
              Prefer to use variable instead of array it s faster.






              share|improve this answer









              $endgroup$















                0












                0








                0





                $begingroup$

                You should copy your page and write the time taken for all file-get-content and for the query. So you ll know where come that it s very slow.
                How many people are using it? How many people are using your server? If too many it s saturated and very very slow : change your server or the internet connection or optimise your code.
                Next use echo to write text it s faster than stoping the script and coming back.
                Better to redo a sql query instead of downloading a file. You could also cache the most used queries eventually in a new database table.
                If using the script tag you should always inform what is the language.
                If you use only once a session variable, it s faster not to save it first in a variable.
                If you just need to display a value only don t save it in an array first but at the moment of running the query.
                Prefer to use variable instead of array it s faster.






                share|improve this answer









                $endgroup$



                You should copy your page and write the time taken for all file-get-content and for the query. So you ll know where come that it s very slow.
                How many people are using it? How many people are using your server? If too many it s saturated and very very slow : change your server or the internet connection or optimise your code.
                Next use echo to write text it s faster than stoping the script and coming back.
                Better to redo a sql query instead of downloading a file. You could also cache the most used queries eventually in a new database table.
                If using the script tag you should always inform what is the language.
                If you use only once a session variable, it s faster not to save it first in a variable.
                If you just need to display a value only don t save it in an array first but at the moment of running the query.
                Prefer to use variable instead of array it s faster.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Feb 18 '18 at 21:10









                user9181232user9181232

                111




                111



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    Use MathJax to format equations. MathJax reference.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f187809%2fdisplaying-the-value-of-a-stock-portfolio%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

                    Prove that NP is closed under karp reduction?Space(n) not closed under Karp reductions - what about NTime(n)?Class P is closed under rotation?Prove or disprove that $NL$ is closed under polynomial many-one reductions$mathbfNC_2$ is closed under log-space reductionOn Karp reductionwhen can I know if a class (complexity) is closed under reduction (cook/karp)Check if class $PSPACE$ is closed under polyonomially space reductionIs NPSPACE also closed under polynomial-time reduction and under log-space reduction?Prove PSPACE is closed under complement?Prove PSPACE is closed under union?

                    Is my guitar’s action too high? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Strings too stiff on a recently purchased acoustic guitar | Cort AD880CEIs the action of my guitar really high?Μy little finger is too weak to play guitarWith guitar, how long should I give my fingers to strengthen / callous?When playing a fret the guitar sounds mutedPlaying (Barre) chords up the guitar neckI think my guitar strings are wound too tight and I can't play barre chordsF barre chord on an SG guitarHow to find to the right strings of a barre chord by feel?High action on higher fret on my steel acoustic guitar