/**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $this->info("This is involves downloading and storing several million records. This may take several hours...");
     if ($this->confirm('Do you wish to continue?')) {
         $this->info("Downloading historical financials...");
         $numberOfStocks = Stock::count();
         foreach (Stock::lists('stock_code') as $key => $stockCode) {
             if (!Historicals::where(['stock_code' => $stockCode, 'date' => '2015-08-11'])->first()) {
                 $historicalSheetUrl = "http://real-chart.finance.yahoo.com/table.csv?s=" . $stockCode . ".AX&d=7&e=12&f=2015&g=d&a=7&b=11&c=2015&ignore=.csv";
                 if (get_headers($historicalSheetUrl, 1)[0] == 'HTTP/1.1 200 OK') {
                     file_put_contents('database/files/spreadsheet.txt', trim(str_replace("Date,Open,High,Low,Close,Volume,Adj Close", "", file_get_contents($historicalSheetUrl))));
                     $spreadSheetFile = fopen('database/files/spreadsheet.txt', 'r');
                     $dailyTradeRecord = array();
                     while (!feof($spreadSheetFile)) {
                         $line = fgets($spreadSheetFile);
                         $pieces = explode(',', $line);
                         array_push($dailyTradeRecord, array('stock_code' => $stockCode, 'date' => $pieces[0], 'open' => $pieces[1], 'high' => $pieces[2], 'low' => $pieces[3], 'close' => $pieces[4], 'volume' => $pieces[5], 'adj_close' => $pieces[6], 'created_at' => date("Y-m-d H:i:s"), 'updated_at' => date("Y-m-d H:i:s")));
                     }
                     //\DB::table('historicals')->where('stock_code', $stockCode)->delete();
                     \DB::table('historicals')->insert($dailyTradeRecord);
                 }
             }
             $this->info("Completed: " . $stockCode . " " . ($key + 1) . "/" . $numberOfStocks . " - " . round(($key + 1) * (100 / $numberOfStocks), 2) . "%");
         }
         $this->info("The historical financials have been downloaded.");
     }
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     $this->info('Updating stock metrics... This may take several minutes...');
     $iterationNumber = 1;
     $maxIterations = ceil(Stock::count() / 100);
     if ($this->option('testMode')) {
         $maxIterations = 1;
         $this->info("[Test Mode]");
     }
     UpdateStockMetricsCommand::insertMetricRowsForNewStocks();
     while ($iterationNumber <= $maxIterations) {
         $stockCodeParameter = UpdateStockMetricsCommand::getStockCodeParameter($this->option('testMode'));
         $stockURL = "http://finance.yahoo.com/d/quotes.csv?s=" . $stockCodeParameter . "&f=sl1p2a2j4ee8p5rp6kjj1y";
         $metrics = explode("\n", file_get_contents($stockURL));
         foreach ($metrics as $metric) {
             if ($metric != null) {
                 $individualMetric = explode(',', $metric);
                 $stockCode = substr(explode('.', $individualMetric[0])[0], 1);
                 StockMetrics::updateOrCreate(['stock_code' => $stockCode], ["stock_code" => $stockCode, "last_trade" => $individualMetric[1], "day_change" => substr($individualMetric[2], 1, -2), "average_daily_volume" => $individualMetric[3], "EBITDA" => UpdateStockMetricsCommand::formatEBITDA($individualMetric[4]), "earnings_per_share_current" => $individualMetric[5], "earnings_per_share_next_year" => $individualMetric[6], "price_to_sales" => $individualMetric[7], "price_to_earnings" => $individualMetric[8], "price_to_book" => $individualMetric[9], "year_high" => $individualMetric[10], "year_low" => $individualMetric[11], "market_cap" => formatMoneyAmountToNumber($individualMetric[12]), "dividend_yield" => $individualMetric[13], "updated_at" => date("Y-m-d H:i:s")]);
             }
         }
         $this->info("Updating... " . round($iterationNumber * (100 / $maxIterations), 2) . "%");
         $iterationNumber++;
     }
     $this->info('All stock metrics were updated successfully!');
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     if ($this->option('testMode') == 'true') {
         $this->info("[Test Mode]");
         foreach (['TLS', 'CBA'] as $stockCode) {
             $priceOneWeekAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subWeek()));
             $lastTrade = StockMetrics::where('stock_code', $stockCode)->pluck('last_trade');
             $weekChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceOneWeekAgo);
             StockGains::updateOrCreate(['stock_code' => $stockCode], ['stock_code' => $stockCode, 'week_change' => $weekChange, 'updated_at' => date("Y-m-d H:i:s")]);
         }
     } else {
         $this->info("Calculating the stock changes... This may take several minutes.");
         $stockCodes = Stock::lists('stock_code');
         $numberOfStocks = Stock::count();
         //For Calculation of YTD gain
         $firstTradingDateOfYear = CalculateStockChangeCommand::getFirstTradingDateOfYear();
         foreach ($stockCodes as $key => $stockCode) {
             $lastTrade = StockMetrics::where('stock_code', $stockCode)->pluck('last_trade');
             $priceOneWeekAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subWeek()));
             $weekChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceOneWeekAgo);
             $priceTwoWeeksAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subWeeks(2)));
             $twoWeekChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceTwoWeeksAgo);
             $priceOneMonthAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subMonth()));
             $oneMonthChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceOneMonthAgo);
             $priceTwoMonthsAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subMonths(2)));
             $twoMonthChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceTwoMonthsAgo);
             $priceThreeMonthsAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subMonths(3)));
             $threeMonthChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceThreeMonthsAgo);
             $priceSixMonthsAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subMonths(6)));
             $sixMonthChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceSixMonthsAgo);
             $priceAtStartOfYear = CalculateStockChangeCommand::getPriceAtDate($stockCode, $firstTradingDateOfYear);
             $thisYearChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceAtStartOfYear);
             $priceOneYearAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subYear()));
             $oneYearChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceOneYearAgo);
             $priceTwoYearsAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subYears(2)));
             $twoYearChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceTwoYearsAgo);
             $priceThreeYearsAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subYears(3)));
             $threeYearChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceThreeYearsAgo);
             $priceFiveYearsAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subYears(5)));
             $fiveYearChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceFiveYearsAgo);
             $priceTenYearsAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subYears(10)));
             $tenYearChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceTenYearsAgo);
             if (Historicals::where('stock_code', $stockCode)->first()) {
                 $oldestDate = Historicals::where('stock_code', $stockCode)->orderBy('date', 'asc')->take(1)->lists('date');
                 $oldestPriceAvailable = CalculateStockChangeCommand::getPriceAtDate($stockCode, substr($oldestDate, 2, -2));
                 $allTimeChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $oldestPriceAvailable);
             } else {
                 $allTimeChange = 0;
             }
             StockGains::updateOrCreate(['stock_code' => $stockCode], ['stock_code' => $stockCode, 'week_change' => $weekChange, 'two_week_change' => $twoWeekChange, 'month_change' => $oneMonthChange, 'two_month_change' => $twoMonthChange, 'three_month_change' => $threeMonthChange, 'six_month_change' => $sixMonthChange, 'this_year_change' => $thisYearChange, 'year_change' => $oneYearChange, 'two_year_change' => $twoYearChange, 'three_year_change' => $threeYearChange, 'five_year_change' => $fiveYearChange, 'ten_year_change' => $tenYearChange, 'all_time_change' => $allTimeChange, 'updated_at' => date("Y-m-d H:i:s")]);
             $this->info("Completed: " . $stockCode . " " . ($key + 1) . "/" . $numberOfStocks . " - " . round(($key + 1) * (100 / $numberOfStocks), 2) . "%");
         }
     }
 }