Skip to content

Instantly share code, notes, and snippets.

@thewinterwind
Last active June 13, 2016 13:56
Show Gist options
  • Save thewinterwind/793eeb2ecff957dd0298 to your computer and use it in GitHub Desktop.
Save thewinterwind/793eeb2ecff957dd0298 to your computer and use it in GitHub Desktop.
Code to count streaks in PHP (used with Yahoo API tutorial)
<?php
class StoringController extends BaseController {
public function store_streaks()
{
$date = date('Y-m-d');
$stocks = DB::table('stocks')->select('symbol')->orderBy('symbol', 'asc')->get();
foreach ($stocks as $stock)
{
$stored = DB::table('stocks')
->where('symbol', $stock->symbol)
->where('streak_stored', $date)
->first();
if ($stored) continue;
$days = DB::table('summaries')
->select('close')
->where('symbol', $stock->symbol)
->orderBy('date', 'desc')
->limit(20)
->get();
$streak = 0;
for ($i = 0; $i < count($days); $i++)
{
// if we're at the earliest day recorded for a stock, the streak is over
if ( ! isset($days[$i + 1])) break;
// if the next days price is the same as the current, the streak is over
if ($days[$i]->close === $days[$i + 1]->close) break;
// one time check for the first iteration
if ($i === 0)
{
if ($days[$i] > $days[$i + 1])
{
$streak++; continue;
}
if ($days[$i] < $days[$i + 1])
{
$streak--; continue;
}
}
// check if the winning streak is over or not
if ($streak > 0)
{
// if current day's close is less than the day before it, the winning streak is over
if ($days[$i]->close < $days[$i + 1]->close) break;
// the winning streak continues
$streak++;
}
elseif ($streak < 0)
{
// if the current day's close is more than the day before it, the losing streak is over
if ($days[$i]->close > $days[$i + 1]->close) break;
// the losing streak continues
$streak--;
}
}
DB::table('stocks')
->where('symbol', $stock->symbol)
->update([
'streak' => $streak,
'streak_stored' => $date,
]);
print "Stored a streak of " . $streak . " for: " . $stock->symbol . "\n";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment