refactor: split oil price ingestion and prediction into separate services + commands

- BrentPriceFetcher owns ingestion (fetchFromEia / fetchFromFred, each throws on failure)
- BrentPricePredictor owns prediction and marks latest brent_prices row as generated
- oil:fetch command tries EIA, falls back to FRED, fails loudly if both fail
- oil:predict command prompts if latest price already has a prediction; --force bypasses
- add prediction_generated_at column to brent_prices
- delete OilPriceService (replaced by the two focused services)
This commit is contained in:
Ovidiu U
2026-04-14 16:59:43 +01:00
parent 1a0381265e
commit 486f0e689c
10 changed files with 415 additions and 306 deletions

View File

@@ -0,0 +1,37 @@
<?php
namespace App\Console\Commands;
use App\Services\BrentPriceFetcher;
use App\Services\BrentPriceSources\BrentPriceFetchException;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('oil:fetch')]
#[Description('Fetch latest Brent crude prices (EIA primary, FRED fallback)')]
class FetchOilPrices extends Command
{
public function handle(BrentPriceFetcher $fetcher): int
{
try {
$fetcher->fetchFromEia();
$this->info('Fetched Brent prices from EIA.');
return self::SUCCESS;
} catch (BrentPriceFetchException $e) {
$this->warn('EIA fetch failed: '.$e->getMessage().'. Trying FRED...');
}
try {
$fetcher->fetchFromFred();
$this->info('Fetched Brent prices from FRED.');
return self::SUCCESS;
} catch (BrentPriceFetchException $e) {
$this->error('Both EIA and FRED failed: '.$e->getMessage());
return self::FAILURE;
}
}
}

View File

@@ -2,26 +2,37 @@
namespace App\Console\Commands;
use App\Services\OilPriceService;
use App\Services\BrentPricePredictor;
use Illuminate\Console\Command;
use Throwable;
class PredictOilPrices extends Command
{
protected $signature = 'oil:predict {--fetch : Fetch latest FRED prices before predicting}';
protected $signature = 'oil:predict {--force : Generate even if the latest price already has a prediction}';
protected $description = 'Generate a Brent crude oil price direction prediction';
public function handle(OilPriceService $service): int
public function handle(BrentPricePredictor $predictor): int
{
try {
if ($this->option('fetch')) {
$this->info('Fetching latest Brent crude prices from FRED...');
$service->fetchBrentPrices();
$latest = $predictor->latestPrice();
if ($latest?->prediction_generated_at !== null && ! $this->option('force')) {
$message = sprintf(
'Prediction already generated for %s at %s.',
$latest->date->toDateString(),
$latest->prediction_generated_at->toDateTimeString(),
);
if (! $this->confirm($message.' Run again anyway?', default: false)) {
$this->info('Skipped.');
return self::SUCCESS;
}
}
$this->info('Generating prediction...');
$prediction = $service->generatePrediction();
$prediction = $predictor->generatePrediction();
if ($prediction === null) {
$this->error('Could not generate a prediction — not enough price data.');

View File

@@ -6,9 +6,8 @@ use Database\Factories\BrentPriceFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
#[Fillable(['date', 'price_usd'])]
#[Fillable(['date', 'price_usd', 'prediction_generated_at'])]
class BrentPrice extends Model
{
/** @use HasFactory<BrentPriceFactory> */
@@ -27,6 +26,7 @@ class BrentPrice extends Model
return [
'date' => 'date',
'price_usd' => 'decimal:2',
'prediction_generated_at' => 'datetime',
];
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace App\Services;
use App\Models\BrentPrice;
use App\Services\BrentPriceSources\BrentPriceFetchException;
use App\Services\BrentPriceSources\EiaBrentPriceSource;
use App\Services\BrentPriceSources\FredBrentPriceSource;
final readonly class BrentPriceFetcher
{
public function __construct(
private readonly EiaBrentPriceSource $eia,
private readonly FredBrentPriceSource $fred,
) {}
/**
* Fetch from EIA and persist. Throws on failure.
*/
public function fetchFromEia(): void
{
$rows = $this->eia->fetch();
if ($rows === null) {
throw new BrentPriceFetchException('EIA fetch returned no data');
}
BrentPrice::upsert($rows, ['date'], ['price_usd']);
}
/**
* Fetch from FRED and persist. Throws on failure.
*/
public function fetchFromFred(): void
{
$rows = $this->fred->fetch();
if ($rows === null) {
throw new BrentPriceFetchException('FRED fetch returned no data');
}
BrentPrice::upsert($rows, ['date'], ['price_usd']);
}
}

View File

@@ -6,70 +6,42 @@ use App\Enums\PredictionSource;
use App\Enums\TrendDirection;
use App\Models\BrentPrice;
use App\Models\PricePrediction;
use App\Services\BrentPriceSources\EiaBrentPriceSource;
use App\Services\BrentPriceSources\FredBrentPriceSource;
use App\Services\LlmPrediction\OilPredictionProvider;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
class OilPriceService
final class BrentPricePredictor
{
/**
* Decay factor for EWMA. Higher = more weight on recent prices.
*/
private const float EWMA_ALPHA = 0.3;
/**
* Minimum % change in EWMA to be considered rising/falling.
*/
private const float EWMA_THRESHOLD_PCT = 1.5;
/**
* EWMA confidence is capped lower than LLM it's a simpler model.
*/
private const int EWMA_MAX_CONFIDENCE = 65;
/**
* Minimum price rows needed before EWMA is meaningful.
*/
private const int EWMA_MIN_ROWS = 14;
public function __construct(
private readonly OilPredictionProvider $provider,
private readonly EiaBrentPriceSource $eia,
private readonly FredBrentPriceSource $fred,
) {}
/**
* Fetch the last 30 days of Brent crude prices.
* Tries each configured source in order; upserts the first successful result.
* Return the latest BrentPrice row, or null if none exists.
*/
public function fetchBrentPrices(): void
public function latestPrice(): ?BrentPrice
{
foreach ([$this->eia, $this->fred] as $source) {
$rows = $source->fetch();
if ($rows !== null) {
BrentPrice::upsert($rows, ['date'], ['price_usd']);
return;
}
}
Log::error('OilPriceService: all Brent price sources failed');
return BrentPrice::orderBy('date', 'desc')->first();
}
/**
* Generate predictions from all available sources and store each one.
* EWMA always runs. LLM provider runs and returns null if not configured.
* Returns the highest-confidence prediction (LLM preferred over EWMA).
* Generate EWMA + LLM predictions, store them, and flag the latest
* brent_prices row as having a prediction generated.
*/
public function generatePrediction(): ?PricePrediction
{
$prices = BrentPrice::orderBy('date', 'desc')->limit(30)->get();
if ($prices->count() < self::EWMA_MIN_ROWS) {
Log::warning('OilPriceService: not enough price data to generate prediction', [
Log::warning('BrentPricePredictor: not enough price data', [
'rows' => $prices->count(),
]);
@@ -88,13 +60,15 @@ class OilPriceService
PricePrediction::create($llm->toArray());
}
return $llm ?? $ewma;
$result = $llm ?? $ewma;
if ($result !== null) {
$prices->first()->forceFill(['prediction_generated_at' => now()])->save();
}
return $result;
}
/**
* Option A EWMA-based trend extrapolation. Used as fallback when LLM is unavailable.
* Compares the 3-day EWMA against the 7-day EWMA to detect direction.
*/
public function generateEwmaPrediction(Collection $prices): ?PricePrediction
{
$chronological = $prices->sortBy('date')->pluck('price_usd')->values()->all();
@@ -139,9 +113,7 @@ class OilPriceService
}
/**
* Compute Exponential Weighted Moving Average for a series of prices.
*
* @param float[] $prices Chronological order (oldest first)
* @param float[] $prices Chronological (oldest first).
*/
private function computeEwma(array $prices): float
{
@@ -154,10 +126,6 @@ class OilPriceService
return round($ema, 4);
}
/**
* Map a % change magnitude to a 0EWMA_MAX_CONFIDENCE confidence score.
* 1.5% ~30, 3% ~50, 5%+ 65.
*/
private function ewmaConfidence(float $changePct): int
{
$scaled = min($changePct / 5.0, 1.0) * self::EWMA_MAX_CONFIDENCE;

View File

@@ -0,0 +1,7 @@
<?php
namespace App\Services\BrentPriceSources;
use RuntimeException;
final class BrentPriceFetchException extends RuntimeException {}