Files
investbrain/app/Models/Dividend.php
T

204 lines
6.8 KiB
PHP
Raw Normal View History

2024-08-10 13:30:19 -05:00
<?php
2025-01-28 17:33:54 -06:00
declare(strict_types=1);
2024-08-10 13:30:19 -05:00
namespace App\Models;
2025-04-09 19:25:15 -05:00
use App\Actions\CopyToBaseCurrency;
use App\Casts\BaseCurrency;
2024-08-30 21:58:38 -05:00
use App\Interfaces\MarketData\MarketDataInterface;
2025-04-09 19:25:15 -05:00
use App\Traits\HasMarketData;
2024-08-17 18:40:50 -05:00
use Illuminate\Database\Eloquent\Concerns\HasUuids;
2024-08-10 13:30:19 -05:00
use Illuminate\Database\Eloquent\Factories\HasFactory;
2025-01-28 17:14:49 -06:00
use Illuminate\Database\Eloquent\Model;
2025-04-09 19:25:15 -05:00
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Arr;
2025-01-28 17:14:49 -06:00
use Illuminate\Support\Carbon;
2025-03-10 21:17:24 -05:00
use Illuminate\Support\Facades\DB;
2025-04-09 19:25:15 -05:00
use Illuminate\Support\Facades\Pipeline;
2025-01-28 17:14:49 -06:00
use Illuminate\Support\Str;
2024-08-10 13:30:19 -05:00
class Dividend extends Model
{
use HasFactory;
2025-04-09 19:25:15 -05:00
use HasMarketData;
2024-08-17 18:40:50 -05:00
use HasUuids;
2024-08-10 13:30:19 -05:00
protected $fillable = [
'symbol',
'date',
'dividend_amount',
];
protected $hidden = [];
protected $casts = [
2025-04-09 19:25:15 -05:00
'date' => 'date',
'last_dividend_update' => 'date',
'dividend_amount' => 'float',
'dividend_amount_base' => BaseCurrency::class,
2024-08-10 13:30:19 -05:00
];
2025-04-09 19:25:15 -05:00
protected static function boot()
2025-01-28 17:14:49 -06:00
{
2025-04-09 19:25:15 -05:00
parent::boot();
static::saving(function ($dividend) {
$dividend = Pipeline::send($dividend)
->through([
CopyToBaseCurrency::class,
])
->then(fn (Dividend $dividend) => $dividend);
});
2024-09-01 15:34:55 -05:00
}
2025-04-09 19:25:15 -05:00
public function holdings(): HasMany
2025-01-28 17:14:49 -06:00
{
2024-09-01 15:34:55 -05:00
return $this->hasMany(Holding::class, 'symbol', 'symbol');
}
2025-04-09 19:25:15 -05:00
public function transactions(): HasMany
2025-01-28 17:14:49 -06:00
{
2024-09-01 15:34:55 -05:00
return $this->hasMany(Transaction::class, 'symbol', 'symbol');
}
2024-09-11 21:58:48 -05:00
public function scopeSymbol($query, $symbol)
{
return $query->where('dividends.symbol', $symbol);
}
2024-08-10 13:30:19 -05:00
/**
2024-08-30 21:58:38 -05:00
* Grab new dividend data
2024-08-10 13:30:19 -05:00
*/
public static function refreshDividendData(string $symbol): void
2024-08-10 13:30:19 -05:00
{
2024-08-30 21:58:38 -05:00
$dividends_meta = self::where(['symbol' => $symbol])
->selectRaw('COUNT(symbol) as total_dividends')
->selectRaw('MAX(created_at) as last_dividend_update')
2024-08-30 21:58:38 -05:00
->get()
->first();
// assume we need to populate ALL dividend data
$start_date = new Carbon('@0');
2024-08-30 21:58:38 -05:00
$end_date = now();
// nope, refresh forward looking only
2025-01-28 17:14:49 -06:00
if ($dividends_meta->total_dividends) {
$start_date = $dividends_meta->last_dividend_update;
}
2025-01-28 17:14:49 -06:00
// skip refresh if there's already recent data
if ($start_date->greaterThan($end_date)) {
return;
2024-08-10 13:30:19 -05:00
}
2024-08-30 21:58:38 -05:00
// get some data
if ($dividend_data = collect() && $start_date && $end_date) {
$dividend_data = app(MarketDataInterface::class)->dividends($symbol, $start_date, $end_date);
}
// ah, we found some dividends...
if ($dividend_data->isNotEmpty()) {
2025-04-09 19:25:15 -05:00
$market_data = MarketData::getMarketData($symbol);
2025-05-02 18:14:06 -05:00
$dividend_data
->chunk(10)
->each(function ($chunk) use ($market_data) {
2025-04-09 19:25:15 -05:00
2025-05-02 18:14:06 -05:00
// get historic conversion rates
$rate_to_base = CurrencyRate::timeSeriesRates($market_data->currency, $chunk->min('date'), $chunk->max('date'));
2025-04-09 19:25:15 -05:00
2025-05-02 18:14:06 -05:00
// create mass insert
foreach ($chunk as $index => $dividend) {
$rate_to_base_date = 1 / Arr::get($rate_to_base, Carbon::parse(Arr::get($dividend, 'date'))->toDateString(), 1);
2025-04-09 19:25:15 -05:00
2025-05-02 18:14:06 -05:00
$dividend['dividend_amount_base'] = $dividend['dividend_amount'] * $rate_to_base_date;
2024-08-30 21:58:38 -05:00
2025-05-02 18:14:06 -05:00
$chunk[$index] = [...$dividend, ...['id' => Str::uuid()->toString(), 'updated_at' => now(), 'created_at' => now()]];
}
// insert records
(new self)->insertOrIgnore($chunk->toArray());
});
2024-08-30 21:58:38 -05:00
// sync to holdings
2024-10-18 20:46:22 -05:00
self::syncHoldings($symbol);
2024-08-30 21:58:38 -05:00
2024-10-18 20:46:22 -05:00
// re-invest dividends
self::reinvestDividends($dividend_data, $market_data);
// sync last dividend amount to market data table
2024-09-11 21:58:48 -05:00
$market_data->last_dividend_amount = $dividend_data->sortByDesc('date')->first()['dividend_amount'];
2024-09-01 15:34:55 -05:00
$market_data->save();
2024-08-30 21:58:38 -05:00
}
2024-08-10 13:30:19 -05:00
}
2024-10-18 20:46:22 -05:00
public static function syncHoldings(string $symbol): void
2024-09-01 15:34:55 -05:00
{
// group by holdings
2025-03-10 21:17:24 -05:00
$subQuery = self::select([
'holdings.portfolio_id',
'dividends.date',
'dividends.symbol',
'dividends.dividend_amount',
])->selectRaw("
(COALESCE(SUM(CASE WHEN transactions.transaction_type = 'BUY'
AND date(transactions.date) <= date(dividends.date)
THEN transactions.quantity ELSE 0 END), 0)
- COALESCE(SUM(CASE WHEN transactions.transaction_type = 'SELL'
AND date(transactions.date) <= date(dividends.date)
THEN transactions.quantity ELSE 0 END), 0))
* dividends.dividend_amount
AS total_received
")->join('transactions', 'transactions.symbol', '=', 'dividends.symbol')
2025-01-28 17:14:49 -06:00
->join('holdings', 'transactions.portfolio_id', '=', 'holdings.portfolio_id')
->where('dividends.symbol', $symbol)
2025-04-09 19:25:15 -05:00
->groupBy('holdings.portfolio_id', 'dividends.date', 'dividends.symbol', 'dividends.dividend_amount', 'dividends.dividend_amount_base');
2025-03-10 21:17:24 -05:00
$dividends = DB::table(DB::raw("({$subQuery->toSql()}) as sub"))
->mergeBindings($subQuery->getQuery())
->where('total_received', '>', 0)
2025-01-28 17:14:49 -06:00
->get();
// iterate through holdings and update
2024-09-01 15:34:55 -05:00
Holding::where(['symbol' => $symbol])
2025-01-28 17:14:49 -06:00
->get()
->each(function ($holding) use ($dividends) {
$holding->update([
'dividends_earned' => $dividends->where('portfolio_id', $holding->portfolio_id)
->sum('total_received'),
]);
});
2024-08-10 13:30:19 -05:00
}
2024-10-18 20:46:22 -05:00
public static function reinvestDividends(iterable $dividend_data, MarketData $market_data): void
{
// re-invest dividends
Holding::where([
'symbol' => $market_data->symbol,
'reinvest_dividends' => true,
])
2025-01-28 17:14:49 -06:00
->get()
->each(function ($holding) use ($dividend_data, $market_data) {
foreach ($dividend_data as $dividend) {
Transaction::create([
'date' => $dividend['date'],
'portfolio_id' => $holding->portfolio_id,
'symbol' => $holding->symbol,
2025-05-02 18:14:06 -05:00
'currency' => $holding->market_data->currency,
2025-01-28 17:14:49 -06:00
'transaction_type' => 'BUY',
'reinvested_dividend' => true,
'cost_basis' => 0,
'quantity' => ($dividend['dividend_amount'] * $holding->qtyOwned(Carbon::parse($dividend['date']))) / $market_data->market_value,
]);
}
});
2024-10-18 20:46:22 -05:00
}
2024-08-10 13:30:19 -05:00
}