I am trying to get DividendYield from a company for the last 20 years using ChartJs in laravel project. The arrays came from HTTP client API. The formula is like that :$dividendPayed / $dailyPrice * 100. The problem i am facing is that the $dividendPayed is once in three months so it makes that array shorter that the one which contains daily prices.
private function getDividend()
{
$dividend = [];
$response = Http::get('https://some-endpoint-for-once-in-3-months-dividend');
$response->throw();
foreach($response->json('historical') as $stock){
$dividend [] = $stock['dividend'];
}
return $dividend;
//THIS ARRAY RETURNS LET'S SAY FOR EXAMPLE 50 RESULTS
// $dividend = [
0 => 0.23
1 => 0.23
2 => 0.22
3 => 0.22
..........
50 => .43
]
}
private function getPrice()
{
$price = [];
$response = Http::get('https://some-endpoint-for-daily-prices');
$response->throw();
foreach($response->json('historical') as $stockPrice){
$price [] = $stockPrice['close'];
}
return $price;
}
//THIS ARRAY RETURNS LET'S SAY FOR EXAMPLE 240 RESULTS
// $price = [
0 => 147.27
1 => 143.39
2 => 143.86
3 => 143.75
4 => 142.41
5 => 138.38
..........
240 => 300.43
]
I also have to mention that the ‘date’ in the chart for labels (day by day for the last 20 years) is taken from the same endpoint as $dailyPrice.
2
Answers
Since you didn’t mention the full response from https://some-endpoint-for-once-in-3-months-dividend and https://some-endpoint-for-daily-prices. Im assuming a date key exists with the responses for example
For fetching the API responses
For calculating the DividendYield
So first you need to group your
$price
by month, assuming that thedd()
in your comment is whatprice
is, by using:then you need to loop through the
$dividend
:The
$price[key]
means the month group we want, so ifkey = 0
that means we are looping the first month.I hope i get you right, feel free to comment on this to help me understand you more if i’m wrong.