Files
investbrain/app/Models/MarketData.php
T

78 lines
1.8 KiB
PHP
Raw Normal View History

2024-08-10 13:30:19 -05:00
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Interfaces\MarketData\MarketDataInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class MarketData extends Model
{
use HasFactory;
protected $primaryKey = 'symbol';
protected $keyType = 'string';
public $incrementing = false;
protected $fillable = [
'symbol',
'name',
'market_value',
'fifty_two_week_high',
'fifty_two_week_low',
2024-08-24 22:19:40 -05:00
'forward_pe',
'trailing_pe',
'market_cap'
2024-08-10 13:30:19 -05:00
];
public static function setSplitsHoldingSynced($symbol)
{
$market_data = self::where('symbol', $symbol)->get()->first();
$market_data->splits_synced_to_holdings_at = now();
$market_data->save();
}
public function refreshMarketData()
{
return static::getMarketData($this->attributes['symbol']);
}
public static function getMarketData($symbol)
{
$market_data = self::firstOrNew([
'symbol' => $symbol
]);
2024-08-10 13:30:19 -05:00
// check if new or stale
2024-08-24 22:19:40 -05:00
if (
!$market_data->exists
|| is_null($market_data->updated_at)
|| $market_data->updated_at->diffInMinutes(now()) >= config('market_data.refresh')
) {
2024-08-10 13:30:19 -05:00
// get quote
2024-08-24 22:19:40 -05:00
$quote = app(MarketDataInterface::class)->quote($symbol);
2024-08-10 13:30:19 -05:00
// fill data
2024-08-24 22:19:40 -05:00
$market_data->fill($quote->toArray());
2024-08-10 13:30:19 -05:00
}
// save with timestamps updated
$market_data->touch();
2024-08-10 13:30:19 -05:00
return $market_data;
}
public function holdings()
{
return $this->hasMany(Holding::class, 'symbol', 'symbol');
}
public function scopeSymbol($query, $symbol)
{
return $query->where('symbol', $symbol);
}
}