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,120 @@
<?php
use App\Models\BrentPrice;
use App\Services\ApiLogger;
use App\Services\BrentPriceFetcher;
use App\Services\BrentPriceSources\BrentPriceFetchException;
use App\Services\BrentPriceSources\EiaBrentPriceSource;
use App\Services\BrentPriceSources\FredBrentPriceSource;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
uses(RefreshDatabase::class);
beforeEach(function (): void {
Http::preventStrayRequests();
$apiLogger = new ApiLogger;
$this->fetcher = new BrentPriceFetcher(
new EiaBrentPriceSource($apiLogger),
new FredBrentPriceSource($apiLogger),
);
});
it('fetches and stores brent prices from EIA', function (): void {
Http::fake([
'*eia.gov/*' => Http::response([
'response' => [
'data' => [
['period' => '2026-04-02', 'value' => '73.80'],
['period' => '2026-04-01', 'value' => '75.10'],
],
],
]),
]);
$this->fetcher->fetchFromEia();
expect(BrentPrice::count())->toBe(2)
->and(BrentPrice::find('2026-04-02')->price_usd)->toBe('73.80');
});
it('throws when EIA returns a 500', function (): void {
Http::fake(['*eia.gov/*' => Http::response([], 500)]);
$this->fetcher->fetchFromEia();
})->throws(BrentPriceFetchException::class);
it('throws when EIA returns empty data', function (): void {
Http::fake(['*eia.gov/*' => Http::response(['response' => ['data' => []]])]);
$this->fetcher->fetchFromEia();
})->throws(BrentPriceFetchException::class);
it('filters out EIA missing value markers', function (): void {
Http::fake([
'*eia.gov/*' => Http::response([
'response' => [
'data' => [
['period' => '2026-04-01', 'value' => '75.10'],
['period' => '2026-04-02', 'value' => '.'],
['period' => '2026-04-03', 'value' => '74.20'],
],
],
]),
]);
$this->fetcher->fetchFromEia();
expect(BrentPrice::count())->toBe(2)
->and(BrentPrice::find('2026-04-02'))->toBeNull();
});
it('fetches and stores brent prices from FRED', function (): void {
Http::fake([
'*/fred/series/observations*' => Http::response([
'observations' => [
['date' => '2026-04-01', 'value' => '75.10'],
['date' => '2026-04-02', 'value' => '73.80'],
],
]),
]);
$this->fetcher->fetchFromFred();
expect(BrentPrice::count())->toBe(2);
});
it('throws when FRED fails', function (): void {
Http::fake(['*/fred/series/observations*' => Http::response([], 500)]);
$this->fetcher->fetchFromFred();
})->throws(BrentPriceFetchException::class);
it('filters out FRED missing value markers', function (): void {
Http::fake([
'*/fred/series/observations*' => Http::response([
'observations' => [
['date' => '2026-04-01', 'value' => '75.10'],
['date' => '2026-04-02', 'value' => '.'],
],
]),
]);
$this->fetcher->fetchFromFred();
expect(BrentPrice::count())->toBe(1);
});
it('upserts existing rows on refetch', function (): void {
Http::fake([
'*eia.gov/*' => Http::sequence()
->push(['response' => ['data' => [['period' => '2026-04-01', 'value' => '74.00']]]])
->push(['response' => ['data' => [['period' => '2026-04-01', 'value' => '75.50']]]]),
]);
$this->fetcher->fetchFromEia();
$this->fetcher->fetchFromEia();
expect(BrentPrice::count())->toBe(1)
->and(BrentPrice::find('2026-04-01')->price_usd)->toBe('75.50');
});

View File

@@ -0,0 +1,144 @@
<?php
use App\Enums\PredictionSource;
use App\Enums\TrendDirection;
use App\Models\BrentPrice;
use App\Models\PricePrediction;
use App\Services\BrentPricePredictor;
use App\Services\LlmPrediction\OilPredictionProvider;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function (): void {
$this->provider = Mockery::mock(OilPredictionProvider::class);
$this->predictor = new BrentPricePredictor($this->provider);
});
it('detects a rising trend when 3-day EWMA exceeds 7-day EWMA by threshold', function (): void {
$prices = collect(range(1, 14))->map(fn (int $i) => new BrentPrice([
'date' => now()->subDays(14 - $i)->toDateString(),
'price_usd' => 70.0 + ($i * 2.0),
]));
$prediction = $this->predictor->generateEwmaPrediction($prices);
expect($prediction->direction)->toBe(TrendDirection::Rising)
->and($prediction->source)->toBe(PredictionSource::Ewma)
->and($prediction->confidence)->toBeGreaterThan(0)
->and($prediction->confidence)->toBeLessThanOrEqual(65);
});
it('detects a falling trend when 3-day EWMA falls below 7-day EWMA by threshold', function (): void {
$prices = collect(range(1, 14))->map(fn (int $i) => new BrentPrice([
'date' => now()->subDays(14 - $i)->toDateString(),
'price_usd' => 85.0 - ($i * 2.0),
]));
$prediction = $this->predictor->generateEwmaPrediction($prices);
expect($prediction->direction)->toBe(TrendDirection::Falling);
});
it('returns flat when price movement is within threshold', function (): void {
$prices = collect(range(1, 14))->map(fn (int $i) => new BrentPrice([
'date' => now()->subDays(14 - $i)->toDateString(),
'price_usd' => 75.0 + (($i % 2 === 0) ? 0.1 : -0.1),
]));
$prediction = $this->predictor->generateEwmaPrediction($prices);
expect($prediction->direction)->toBe(TrendDirection::Flat)
->and($prediction->confidence)->toBe(50);
});
it('returns null when fewer than 14 prices are available for EWMA', function (): void {
$prices = collect(range(1, 10))->map(fn (int $i) => new BrentPrice([
'date' => now()->subDays(10 - $i)->toDateString(),
'price_usd' => 75.0,
]));
expect($this->predictor->generateEwmaPrediction($prices))->toBeNull();
});
it('stores both EWMA and LLM predictions when provider succeeds', function (): void {
seedPrices(20);
$this->provider->shouldReceive('predict')->once()->andReturn(new PricePrediction([
'predicted_for' => now()->toDateString(),
'source' => PredictionSource::LlmWithContext,
'direction' => TrendDirection::Rising,
'confidence' => 70,
'reasoning' => 'Trend is up.',
'generated_at' => now(),
]));
$prediction = $this->predictor->generatePrediction();
expect($prediction->source)->toBe(PredictionSource::LlmWithContext)
->and(PricePrediction::count())->toBe(2);
});
it('falls back to EWMA when provider returns null', function (): void {
seedPrices(20, slope: 0.8);
$this->provider->shouldReceive('predict')->once()->andReturn(null);
$prediction = $this->predictor->generatePrediction();
expect($prediction->source)->toBe(PredictionSource::Ewma)
->and(PricePrediction::count())->toBe(1);
});
it('returns null when there is insufficient price data', function (): void {
BrentPrice::insert([
['date' => now()->subDays(2)->toDateString(), 'price_usd' => 75.0],
['date' => now()->subDay()->toDateString(), 'price_usd' => 76.0],
]);
$this->provider->shouldNotReceive('predict');
expect($this->predictor->generatePrediction())->toBeNull()
->and(PricePrediction::count())->toBe(0);
});
it('flags latest brent price as prediction generated on success', function (): void {
seedPrices(20);
$this->provider->shouldReceive('predict')->once()->andReturn(null);
$this->predictor->generatePrediction();
$latest = BrentPrice::orderBy('date', 'desc')->first();
expect($latest->prediction_generated_at)->not->toBeNull();
});
it('does not flag when prediction cannot be generated', function (): void {
BrentPrice::insert([
['date' => now()->subDay()->toDateString(), 'price_usd' => 75.0],
]);
$this->provider->shouldNotReceive('predict');
$this->predictor->generatePrediction();
expect(BrentPrice::first()->prediction_generated_at)->toBeNull();
});
it('returns the latest price row', function (): void {
seedPrices(3);
expect($this->predictor->latestPrice())->not->toBeNull()
->and($this->predictor->latestPrice()->date->toDateString())->toBe(now()->toDateString());
});
function seedPrices(int $count, float $slope = 1.0): void
{
BrentPrice::insert(
collect(range(1, $count))->map(fn (int $i) => [
'date' => now()->subDays($count - $i)->toDateString(),
'price_usd' => 75.0 + ($i * $slope),
])->all()
);
}

View File

@@ -1,250 +0,0 @@
<?php
use App\Enums\PredictionSource;
use App\Enums\TrendDirection;
use App\Models\BrentPrice;
use App\Models\PricePrediction;
use App\Services\ApiLogger;
use App\Services\BrentPriceSources\EiaBrentPriceSource;
use App\Services\BrentPriceSources\FredBrentPriceSource;
use App\Services\LlmPrediction\OilPredictionProvider;
use App\Services\OilPriceService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
uses(RefreshDatabase::class);
beforeEach(function (): void {
Http::preventStrayRequests();
$this->provider = Mockery::mock(OilPredictionProvider::class);
$apiLogger = new ApiLogger;
$this->service = new OilPriceService(
$this->provider,
new EiaBrentPriceSource($apiLogger),
new FredBrentPriceSource($apiLogger),
);
});
// --- fetchBrentPrices ---
it('fetches and stores brent prices from EIA when EIA succeeds', function (): void {
Http::fake([
'*eia.gov/*' => Http::response([
'response' => [
'data' => [
['period' => '2026-04-02', 'value' => '73.80'],
['period' => '2026-04-01', 'value' => '75.10'],
['period' => '2026-03-31', 'value' => '74.50'],
],
],
]),
'*/fred/*' => Http::response([], 500),
]);
$this->service->fetchBrentPrices();
expect(BrentPrice::count())->toBe(3)
->and(BrentPrice::find('2026-04-02')->price_usd)->toBe('73.80');
Http::assertNotSent(fn ($request) => str_contains($request->url(), 'stlouisfed'));
});
it('falls back to FRED when EIA returns a 500', function (): void {
Http::fake([
'*eia.gov/*' => Http::response([], 500),
'*/fred/series/observations*' => Http::response([
'observations' => [
['date' => '2026-04-01', 'value' => '75.10'],
['date' => '2026-04-02', 'value' => '73.80'],
],
]),
]);
$this->service->fetchBrentPrices();
expect(BrentPrice::count())->toBe(2);
});
it('falls back to FRED when EIA returns empty data', function (): void {
Http::fake([
'*eia.gov/*' => Http::response(['response' => ['data' => []]]),
'*/fred/series/observations*' => Http::response([
'observations' => [
['date' => '2026-04-01', 'value' => '75.10'],
],
]),
]);
$this->service->fetchBrentPrices();
expect(BrentPrice::count())->toBe(1);
});
it('stores no rows and logs error when both EIA and FRED fail', function (): void {
Http::fake([
'*eia.gov/*' => Http::response([], 500),
'*/fred/series/observations*' => Http::response([], 500),
]);
$this->service->fetchBrentPrices();
expect(BrentPrice::count())->toBe(0);
});
it('filters out EIA missing value markers', function (): void {
Http::fake([
'*eia.gov/*' => Http::response([
'response' => [
'data' => [
['period' => '2026-04-01', 'value' => '75.10'],
['period' => '2026-04-02', 'value' => '.'],
['period' => '2026-04-03', 'value' => '74.20'],
],
],
]),
]);
$this->service->fetchBrentPrices();
expect(BrentPrice::count())->toBe(2)
->and(BrentPrice::find('2026-04-02'))->toBeNull();
});
it('upserts existing brent price rows on refetch via EIA', function (): void {
Http::fake([
'*eia.gov/*' => Http::sequence()
->push(['response' => ['data' => [['period' => '2026-04-01', 'value' => '74.00']]]])
->push(['response' => ['data' => [['period' => '2026-04-01', 'value' => '75.50']]]]),
]);
$this->service->fetchBrentPrices();
$this->service->fetchBrentPrices();
expect(BrentPrice::count())->toBe(1)
->and(BrentPrice::find('2026-04-01')->price_usd)->toBe('75.50');
});
// --- generateEwmaPrediction ---
it('detects a rising trend when 3-day EWMA exceeds 7-day EWMA by threshold', function (): void {
$prices = collect(range(1, 14))->map(fn (int $i) => new BrentPrice([
'date' => now()->subDays(14 - $i)->toDateString(),
'price_usd' => 70.0 + ($i * 2.0),
]));
$prediction = $this->service->generateEwmaPrediction($prices);
expect($prediction->direction)->toBe(TrendDirection::Rising)
->and($prediction->source)->toBe(PredictionSource::Ewma)
->and($prediction->confidence)->toBeGreaterThan(0)
->and($prediction->confidence)->toBeLessThanOrEqual(65);
});
it('detects a falling trend when 3-day EWMA falls below 7-day EWMA by threshold', function (): void {
$prices = collect(range(1, 14))->map(fn (int $i) => new BrentPrice([
'date' => now()->subDays(14 - $i)->toDateString(),
'price_usd' => 85.0 - ($i * 2.0),
]));
$prediction = $this->service->generateEwmaPrediction($prices);
expect($prediction->direction)->toBe(TrendDirection::Falling)
->and($prediction->source)->toBe(PredictionSource::Ewma);
});
it('returns flat when price movement is within threshold', function (): void {
$prices = collect(range(1, 14))->map(fn (int $i) => new BrentPrice([
'date' => now()->subDays(14 - $i)->toDateString(),
'price_usd' => 75.0 + (($i % 2 === 0) ? 0.1 : -0.1),
]));
$prediction = $this->service->generateEwmaPrediction($prices);
expect($prediction->direction)->toBe(TrendDirection::Flat)
->and($prediction->confidence)->toBe(50);
});
it('returns null when fewer than 14 prices are available for EWMA', function (): void {
$prices = collect(range(1, 10))->map(fn (int $i) => new BrentPrice([
'date' => now()->subDays(10 - $i)->toDateString(),
'price_usd' => 75.0,
]));
expect($this->service->generateEwmaPrediction($prices))->toBeNull();
});
// --- generatePrediction (orchestrator) ---
it('stores both EWMA and LLM predictions when provider succeeds', function (): void {
BrentPrice::insert(
collect(range(1, 20))->map(fn (int $i) => [
'date' => now()->subDays(20 - $i)->toDateString(),
'price_usd' => 75.0 + $i,
])->all()
);
$this->provider->shouldReceive('predict')->once()->andReturn(new PricePrediction([
'predicted_for' => now()->toDateString(),
'source' => PredictionSource::LlmWithContext,
'direction' => TrendDirection::Rising,
'confidence' => 70,
'reasoning' => 'Trend is up.',
'generated_at' => now(),
]));
$prediction = $this->service->generatePrediction();
expect($prediction->source)->toBe(PredictionSource::LlmWithContext)
->and(PricePrediction::count())->toBe(2);
});
it('returns LLM prediction when provider succeeds', function (): void {
BrentPrice::insert(
collect(range(1, 20))->map(fn (int $i) => [
'date' => now()->subDays(20 - $i)->toDateString(),
'price_usd' => 75.0 + $i,
])->all()
);
$llmPrediction = new PricePrediction([
'predicted_for' => now()->toDateString(),
'source' => PredictionSource::Llm,
'direction' => TrendDirection::Rising,
'confidence' => 65,
'reasoning' => 'Rising trend.',
'generated_at' => now(),
]);
$this->provider->shouldReceive('predict')->once()->andReturn($llmPrediction);
$prediction = $this->service->generatePrediction();
expect($prediction->source)->toBe(PredictionSource::Llm);
});
it('falls back to EWMA when provider returns null', function (): void {
BrentPrice::insert(
collect(range(1, 20))->map(fn (int $i) => [
'date' => now()->subDays(20 - $i)->toDateString(),
'price_usd' => 75.0 + ($i * 0.8),
])->all()
);
$this->provider->shouldReceive('predict')->once()->andReturn(null);
$prediction = $this->service->generatePrediction();
expect($prediction->source)->toBe(PredictionSource::Ewma)
->and(PricePrediction::count())->toBe(1);
});
it('returns null when there is insufficient price data', function (): void {
BrentPrice::insert([
['date' => now()->subDays(2)->toDateString(), 'price_usd' => 75.0],
['date' => now()->subDay()->toDateString(), 'price_usd' => 76.0],
]);
$this->provider->shouldNotReceive('predict');
expect($this->service->generatePrediction())->toBeNull()
->and(PricePrediction::count())->toBe(0);
});