/**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $this->info("Updating " . $this->option('mode') . " sector metrics. This may take several minutes...");
     $listOfSectors = Stock::getListOfSectors();
     array_push($listOfSectors, 'All');
     if ($this->option('testMode') == 'true') {
         $this->info("Running in test mode. Only Banks and Telcos will be updated.");
         $listOfSectors = ['Banks', 'Telecommunication Services'];
     }
     foreach ($listOfSectors as $sectorName) {
         $stocksInSector = Stock::where('sector', $sectorName)->lists('stock_code');
         if ($sectorName == 'All') {
             $stocksInSector = Stock::lists('stock_code');
         }
         if (count($stocksInSector) > 0) {
             $totalSectorMarketCap = SectorHistoricals::getTotalSectorMarketCap($stocksInSector);
             if (isTradingDay()) {
                 SectorHistoricals::updateOrCreate(['sector' => $sectorName, 'date' => date("Y-m-d")], ['sector' => $sectorName, 'date' => date("Y-m-d"), 'total_sector_market_cap' => $totalSectorMarketCap, 'day_change' => round(SectorHistoricals::getSectorPercentChange($sectorName, $stocksInSector), 2), 'average_sector_market_cap' => $totalSectorMarketCap / count($stocksInSector)]);
                 if ($this->option('mode') == 'full') {
                     foreach ($this->sectorMetrics as $metricName) {
                         SectorHistoricals::updateOrCreate(['sector' => $sectorName, 'date' => date("Y-m-d")], [$metricName => round(StockMetrics::getAverageMetric($metricName, $stocksInSector, $sectorName), 2)]);
                     }
                 }
             }
         }
     }
 }
 public static function getAverageMetric($metricName, $listOfStocks, $sectorName)
 {
     $sectorMetrics = array();
     foreach ($listOfStocks as $stock) {
         $sectorMetric = StockMetrics::where('stock_code', $stock)->pluck($metricName);
         array_push($sectorMetrics, $sectorMetric);
     }
     return array_sum($sectorMetrics) / count($sectorMetrics);
 }
 public function show(SearchRequest $request)
 {
     $stocks = StockMetrics::getMetricsByStockList($this->search->getSearchResults($request), $request->omitCondition);
     if ($request->viewType == 'partial') {
         if ($request->section == 'sectorDayGain' || $request->section == 'sectorDayLoss') {
             return view('layouts.partials.sector-day-change-display')->with(['sectorChanges' => SectorHistoricals::getSectorDayChanges($request->section), 'title' => SectorHistoricals::getSectorDayChangeTitle($request->section)]);
         }
         return view('layouts.partials.stock-list-display')->with(['stocks' => $stocks]);
     }
     return view('pages.stocks')->with(['stocks' => $stocks, 'stockSectors' => Stock::getSectorDropdown(), 'stockSectorName' => $request->stockSector]);
 }
 /**
  * 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) . "%");
         }
     }
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     if ($this->option('testMode') == 'true') {
         $this->info("[Test Mode]");
         StockMetrics::whereIn('stock_code', ['TLS', 'CBA'])->where('day_change', '!=', 0)->update(['day_change' => 0.0]);
         $this->info("Gains reset for TLS and CBA.");
     } else {
         $this->info("Resetting day gain to 0.00% for all stocks.");
         StockMetrics::where('day_change', '!=', 0)->update(['day_change' => 0.0]);
         $this->info("All gains have been reset.");
     }
 }
 private static function getStockCodeParameter($testMode = false)
 {
     if (!$testMode) {
         //Limit of 100 at a time due to yahoo's url length limit
         $stockCodeList = StockMetrics::where('updated_at', '<', Carbon::now()->subSeconds(60))->orderBy('updated_at')->take(100)->lists('stock_code');
         $stockCodeParameter = "";
         foreach ($stockCodeList as $stockCode) {
             $stockCodeParameter .= "+" . $stockCode . ".AX";
         }
         return substr($stockCodeParameter, 1);
     } else {
         return "TLS.AX+CBA.AX";
     }
 }
 public static function getGraphData($stockCode, $timeFrame = 'last_month', $dataType)
 {
     $historicals = Historicals::where(['stock_code' => $stockCode])->dateCondition($timeFrame)->orderBy('date')->get();
     $graphData = array();
     foreach ($historicals as $record) {
         if ($dataType == 'Price') {
             $price = $record->close;
             $fiftyDayMovingAverage = $record->fifty_day_moving_average;
             $twoHundredDayMovingAverage = $record->two_hundred_day_moving_average;
         }
         array_push($graphData, array(getCarbonDateFromDate($record->date)->toFormattedDateString(), $price, $fiftyDayMovingAverage, $twoHundredDayMovingAverage));
     }
     //Add Current day's trade value to graph data
     //10:32am allows time for the metrics to be populated
     if (isTradingDay() && getCurrentTimeIntVal() >= 103200 && !Historicals::where(['stock_code' => $stockCode, 'date' => date('Y-m-d')])->first()) {
         $stockMetric = StockMetrics::where('stock_code', $stockCode)->first();
         $metricDate = explode(" ", $stockMetric->updated_at)[0];
         array_push($graphData, array(getCarbonDateFromDate($metricDate)->toFormattedDateString(), $stockMetric->last_trade));
     }
     return $graphData;
 }
 private static function calculateDayGain($listOfStocks, $sectorName, $providedDate)
 {
     $marketCaps = array();
     $marketCapDayChanges = array();
     foreach ($listOfStocks as $stock) {
         $marketCap = StockMetrics::where('stock_code', $stock)->pluck('market_cap');
         $open = Historicals::where('stock_code', $stock)->where('date', $providedDate)->pluck('open');
         $close = Historicals::where('stock_code', $stock)->where('date', $providedDate)->pluck('close');
         $dayChange = FillSectorHistoricalsCommand::getDayChange($open, $close);
         array_push($marketCaps, $marketCap);
         array_push($marketCapDayChanges, $marketCap - $marketCap / ($dayChange / 100 + 1));
     }
     $totalSectorMarketCaps = array_sum($marketCaps);
     $totalSectorDayChange = array_sum($marketCapDayChanges);
     if ($totalSectorMarketCaps > 0) {
         $percentChange = 100 / $totalSectorMarketCaps * $totalSectorDayChange;
     } else {
         $percentChange = 0;
     }
     SectorHistoricals::updateOrCreate(['sector' => $sectorName, 'date' => $providedDate], ['sector' => $sectorName, 'date' => $providedDate, 'day_change' => round($percentChange, 2)]);
 }
 public static function getTotalSectorMarketCap($stocksInSector)
 {
     return StockMetrics::whereIn('stock_code', $stocksInSector)->sum('market_cap');
 }
 public function getSearchResults($request)
 {
     $allSectors = [];
     $minPrice = StockMetrics::min('last_trade');
     $maxPrice = StockMetrics::max('last_trade');
     $minVolume = StockMetrics::min('average_daily_volume');
     $maxVolume = StockMetrics::max('average_daily_volume');
     $minEBITDA = StockMetrics::min('EBITDA');
     $maxEBITDA = StockMetrics::max('EBITDA');
     $minEPSCurrentYear = StockMetrics::min('earnings_per_share_current');
     $maxEPSCurrentYear = StockMetrics::max('earnings_per_share_current');
     $minEPSNextYear = StockMetrics::min('earnings_per_share_next_year');
     $maxEPSNextYear = StockMetrics::max('earnings_per_share_next_year');
     $minPERatio = StockMetrics::min('price_to_earnings');
     $maxPERatio = StockMetrics::max('price_to_earnings');
     $minPriceBook = StockMetrics::min('price_to_book');
     $maxPriceBook = StockMetrics::max('price_to_book');
     $min52WeekHigh = StockMetrics::min('year_high');
     $max52WeekHigh = StockMetrics::max('year_high');
     $min52WeekLow = StockMetrics::min('year_low');
     $max52WeekLow = StockMetrics::max('year_low');
     $minMarketCap = StockMetrics::min('market_cap');
     $maxMarketCap = StockMetrics::max('market_cap');
     $minDividendYield = StockMetrics::min('dividend_yield');
     $maxDividendYield = StockMetrics::max('dividend_yield');
     if ($request->minPrice != null) {
         $minPrice = $request->minPrice;
     }
     if ($request->maxPrice != null) {
         $maxPrice = $request->maxPrice;
     }
     if ($request->minVolume != null) {
         $minVolume = $request->minVolume;
     }
     if ($request->maxVolume != null) {
         $maxVolume = $request->maxVolume;
     }
     if ($request->minEBITDA != null) {
         $minEBITDA = $request->minEBITDA;
     }
     if ($request->maxEBITDA != null) {
         $maxEBITDA = $request->maxEBITDA;
     }
     if ($request->minEPSCurrentYear != null) {
         $minEPSCurrentYear = $request->minEPSCurrentYear;
     }
     if ($request->maxEPSCurrentYear != null) {
         $maxEPSCurrentYear = $request->maxEPSCurrentYear;
     }
     if ($request->minEPSNextYear != null) {
         $minEPSNextYear = $request->minEPSNextYear;
     }
     if ($request->maxEPSNextYear != null) {
         $maxEPSNextYear = $request->maxEPSNextYear;
     }
     if ($request->minPERatio != null) {
         $minPERatio = $request->minPERatio;
     }
     if ($request->maxPERatio != null) {
         $maxPERatio = $request->maxPERatio;
     }
     if ($request->minPriceBook != null) {
         $minPriceBook = $request->minPriceBook;
     }
     if ($request->maxPriceBook != null) {
         $maxPriceBook = $request->maxPriceBook;
     }
     if ($request->min52WeekHigh != null) {
         $min52WeekHigh = $request->min52WeekHigh;
     }
     if ($request->max52WeekHigh != null) {
         $max52WeekHigh = $request->max52WeekHigh;
     }
     if ($request->min52WeekLow != null) {
         $min52WeekLow = $request->min52WeekLow;
     }
     if ($request->max52WeekLow != null) {
         $max52WeekLow = $request->max52WeekLow;
     }
     if ($request->minMarketCap != null) {
         $minMarketCap = $request->minMarketCap;
     }
     if ($request->maxMarketCap != null) {
         $maxMarketCap = $request->maxMarketCap;
     }
     if ($request->minDividendYield != null) {
         $minDividendYield = $request->minDividendYield;
     }
     if ($request->maxDividendYield != null) {
         $maxDividendYield = $request->maxDividendYield;
     }
     if ($request->stockSector == null) {
         $request->stockSector = "All";
     }
     //Omit results if box isn't ticked.
     if ($request->omitCondition == null) {
         $request->omitCondition = 'omit';
     }
     return StockMetrics::whereIn('stock_code', $this->getStocksBySector($request->stockSector))->whereBetween('last_trade', [$minPrice, $maxPrice])->whereBetween('average_daily_volume', [$minVolume, $maxVolume])->whereBetween('EBITDA', [$minEBITDA, $maxEBITDA])->whereBetween('earnings_per_share_current', [$minEPSCurrentYear, $maxEPSCurrentYear])->whereBetween('earnings_per_share_next_year', [$minEPSNextYear, $maxEPSNextYear])->whereBetween('price_to_earnings', [$minPERatio, $maxPERatio])->whereBetween('price_to_book', [$minPriceBook, $maxPriceBook])->whereBetween('year_high', [$min52WeekHigh, $max52WeekHigh])->whereBetween('year_low', [$min52WeekLow, $max52WeekLow])->whereBetween('market_cap', [$minMarketCap, $maxMarketCap])->whereBetween('dividend_yield', [$minDividendYield, $maxDividendYield])->omitOutliers($request->omitCondition)->lists('stock_code');
 }
 public function otherStocksInSector($sectorName)
 {
     return view('layouts.partials.other-stocks-in-sector')->with(['selectedSector' => $sectorName, 'stocksInSector' => StockMetrics::getMetricsByStockList(Stock::where('sector', $sectorName)->lists('stock_code'), 'all')]);
 }
 public function stocks()
 {
     $stocks = StockMetrics::with('stock')->orderBy('stock_metrics.market_cap', 'DESC');
     return \Datatables::of($stocks)->make(true);
 }
 public function topGainsLosses()
 {
     $allNonOmittedStocks = StockMetrics::omitOutliers()->lists('stock_code');
     return view('pages.topGainsLosses')->with(['topWeeklyGains' => StockGains::getTopStocksThisWeek($allNonOmittedStocks), 'topWeeklyLosses' => StockGains::getBottomStocksThisWeek($allNonOmittedStocks), 'topMonthlyGains' => StockGains::getTopStocksThisMonth($allNonOmittedStocks), 'topMonthlyLosses' => StockGains::getBottomStocksThisMonth($allNonOmittedStocks), 'topStocks12Months' => StockGains::getTopStocks12Months(29)]);
 }
 public static function getTopStocks12Months($limit = 18)
 {
     $stockList = StockMetrics::omitOutliers()->where('market_cap', '>=', 100)->lists('stock_code');
     return StockGains::whereIn('stock_code', $stockList)->where('year_change', '<', 250)->orderBy('year_change', 'desc')->take($limit)->get();
 }