refactor dividend page

This commit is contained in:
MuslemRahimi 2024-08-23 15:28:46 +02:00
parent 818f3f27bc
commit 969a002b4d
6 changed files with 175 additions and 314 deletions

View File

@ -1,31 +1,20 @@
<script lang="ts">
import {etfTicker, stockTicker, screenWidth} from '$lib/store';
import {etfTicker, screenWidth} from '$lib/store';
import { goto } from '$app/navigation';
import { abbreviateNumber, formatString } from '$lib/utils';
import defaultLogo from '$lib/images/stocks/logo/default_logo.png';
export let dividendList;
let eps;
let currentPrice;
let dividendHistoryList = [];
let dividendYield;
$: {
if($etfTicker && typeof window !== 'undefined')
{
dividendHistoryList = dividendList?.at(0);
eps = dividendList?.at(1)
currentPrice = dividendList?.at(2);
dividendHistoryList = dividendList?.history;
if(dividendHistoryList?.length !== 0)
{
const payoutFrequency = dividendHistoryList?.filter(entry => entry.date.includes('2022'))?.length;
const amount = dividendHistoryList[0]?.adjDividend;
const annualDividend = amount * payoutFrequency
dividendYield = ((annualDividend / currentPrice )*100)?.toFixed(2)
}
dividendYield = dividendList?.dividendYield;
console.log(dividendList)
}
}
@ -34,7 +23,7 @@
<!--Start Similar Stocks Card -->
<div class="space-y-3 lg:pt-5 lg:{dividendList?.length !== 0 ? '' : 'hidden'}">
<div class="space-y-3 lg:pt-5 lg:{dividendHistoryList?.length !== 0 ? '' : 'hidden'}">
<div class="sm:rounded-lg shadow-lg bg-[#000] lg:bg-[#09090B] lg:border lg:border-slate-800 h-auto {$screenWidth <= 800 ? 'w-screen pt-16' : ''} md:w-[400px]">
@ -48,7 +37,7 @@
</span>
</div>
{#if dividendList?.at(0)?.length !== 0}
{#if dividendList?.history?.at(0)?.length !== 0}

View File

@ -773,7 +773,7 @@ $: {
/>
</div>
<div class="{dividendList?.at(0)?.length === 0 ? 'hidden' : ''}">
<div class="{dividendList?.history?.length === 0 ? 'hidden' : ''}">
<DividendCard
dividendList = {dividendList}
/>

View File

@ -11,119 +11,101 @@
export let data;
let isLoaded = false;
let dateDistance;
let stockDividends = data?.getStockDividend?.at(0);
let rawData = data?.getStockDividend;
let optionsDividend;
let exDividendDate = 'n/a';
let dividendYield = 'n/a';
let annualDividend = 'n/a';
let payoutFrequency = 'n/a';
let payoutRatio = 'n/a';
let dividendGrowth = 'n/a';
let dividendList = [];
let growthList = [];
let dateList = [];
let exDividendDate = rawData?.history?.at(0)?.date;
let dividendYield = rawData?.dividendYield;
let annualDividend = rawData?.annualDividend;
let payoutFrequency = rawData?.payoutFrequency;
let payoutRatio = rawData?.payoutRatio;
let dividendGrowth = rawData?.dividendGrowth;
async function plotDividend(dividendList, dateList) {
const options = {
tooltip: {
trigger: 'axis',
hideDelay: 100, // Set the delay in milliseconds
},
animation: false,
grid: {
left: '2%',
right: '0%',
bottom: '10%',
top: '10%',
containLabel: true
},
xAxis: {
data: dateList,
type: 'category',
axisLabel: {
color: '#fff',
},
splitLine: {
show: false, // Disable x-axis grid lines
},
async function plotDividend() {
let dates = [];
let dividendList = [];
// Iterate over the data and extract required information
rawData?.history?.forEach(item => {
dates?.push(item?.paymentDate);
dividendList?.push(item?.adjDividend);
});
dates?.sort((a,b) => new Date(a) - new Date(b));
const options = {
tooltip: {
trigger: 'axis',
hideDelay: 100, // Set the delay in milliseconds
},
yAxis: [
{
type: 'value',
axisLabel: {
color: '#fff',
animation: false,
grid: {
left: '2%',
right: '3%',
bottom: '10%',
top: '10%',
containLabel: true
},
splitLine: {
show: false, // Disable x-axis grid lines
},
},
{
type: 'value',
xAxis: {
data: dates,
type: 'category',
axisLabel: {
show: false,
formatter: '{value} %',
color: '#fff',
},
splitLine: {
show: false,
show: false, // Disable x-axis grid lines
},
},
],
series: [
{
name: 'Dividend per Share',
data: dividendList,
type: 'bar',
smooth: true,
},
],
};
return options;
}
yAxis: [
{
type: 'value',
axisLabel: {
color: '#fff',
},
splitLine: {
show: false, // Disable x-axis grid lines
},
},
{
type: 'value',
axisLabel: {
show: false,
formatter: '{value} %',
},
splitLine: {
show: false,
},
},
],
series: [
{
name: 'Dividend per Share',
data: dividendList,
type: 'bar',
smooth: true,
},
],
};
return options;
}
let syncWorker: Worker | undefined = undefined;
// Handling messages from the worker
const handleMessage = async (event) => {
const finalData = event.data?.finalData
payoutFrequency = finalData?.payoutFrequency;
exDividendDate = finalData?.exDividendDate;
dividendYield = finalData?.dividendYield;
dividendGrowth = finalData?.dividendGrowth;
payoutRatio = finalData?.payoutRatio;
dateDistance = finalData?.dateDistance;
dividendList = finalData?.dividendList;
growthList = finalData?.growthList;
dateList = finalData?.dateList;
annualDividend = finalData?.annualDividend;
optionsDividend = await plotDividend(dividendList, dateList)
//console.log('Message from worker:', chartData);
console.log(dateList)
};
const loadWorker = async () => {
const SyncWorker = await import('./workers/dividendWorker?worker');
syncWorker = new SyncWorker.default();
syncWorker.postMessage({ message: data?.getStockDividend});
syncWorker.onmessage = handleMessage;
};
onMount(async() => {
await loadWorker()
optionsDividend = await plotDividend()
isLoaded = true;
})
@ -155,21 +137,23 @@
<section class="bg-[#09090B] overflow-hidden text-white h-full mb-40 sm:mb-0">
<div class="flex h-full overflow-hidden">
<div class="relative flex justify-center items-center overflow-hidden">
<section class="w-full bg-[#09090B] overflow-hidden text-white h-full mb-40 sm:mb-0">
<div class="w-full flex h-full overflow-hidden">
<div class="w-full relative flex justify-center items-center overflow-hidden">
<div class="sm:p-7 w-full m-auto mt-2 sm:mt-0">
<div class="mb-6">
<div class="w-full mb-6">
<h1 class="text-2xl sm:text-3xl text-gray-200 font-bold mb-4">
Dividends
</h1>
<div class="text-white text-center sm:text-start p-3 sm:p-5 mb-10 rounded-lg sm:flex sm:flex-row sm:items-center border border-slate-800 text-sm sm:text-[1rem]">
<div class="w-full text-white text-start p-3 sm:p-5 mb-10 rounded-lg sm:flex sm:flex-row sm:items-center border border-slate-800 text-sm sm:text-[1rem]">
<svg class="w-6 h-6 flex-shrink-0 inline-block sm:mr-2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256"><path fill="#a474f6" d="M128 24a104 104 0 1 0 104 104A104.11 104.11 0 0 0 128 24m-4 48a12 12 0 1 1-12 12a12 12 0 0 1 12-12m12 112a16 16 0 0 1-16-16v-40a8 8 0 0 1 0-16a16 16 0 0 1 16 16v40a8 8 0 0 1 0 16"/></svg>
{#if stockDividends?.length !== 0}
{#if rawData?.history?.length !== 0}
{#if !dateDistance}
{$displayCompanyName} has an annual dividend of
${annualDividend}
@ -181,21 +165,20 @@
{new Date(exDividendDate)?.toLocaleString('en-US', { month: 'short', day: 'numeric', year: 'numeric', daySuffix: '2-digit' })}
{:else}
{$displayCompanyName} issued its most recent dividend on
{new Date(stockDividends?.at(0)?.date)?.toLocaleString('en-US', { month: 'short', day: 'numeric', year: 'numeric', daySuffix: '2-digit' })}.
{new Date(rawData?.history?.at(0)?.date)?.toLocaleString('en-US', { month: 'short', day: 'numeric', year: 'numeric', daySuffix: '2-digit' })}.
Since then, the company has not distributed any further dividends for over 12 months.
{/if}
{:else}
No dividend history available for {$displayCompanyName}. Likely, the stock has never paid dividends.
No dividend history available for {$displayCompanyName}.
{/if}
</div>
</div>
{#if stockDividends?.length !== 0}
{#if rawData?.history?.length !== 0}
<div class="mb-4 grid grid-cols-2 grid-rows-2 rounded-lg border border-gray-600 bg-[#272727] shadow md:grid-cols-4 md:grid-rows-1">
<div class="p-4 bp:p-5 sm:p-6">
<div class="text-sm font-normal text-default xs:text-base">
@ -251,6 +234,8 @@
</div>
<div class="flex flex-col sm:flex-row items-start sm:items-center w-full mt-14 mb-8">
@ -262,7 +247,9 @@
</div>
{#if stockDividends?.length !== 0 && optionsDividend}
{#if isLoaded}
{#if rawData?.history?.length !== 0 && optionsDividend}
<div class="app w-full">
<Chart {init} options={optionsDividend} class="chart" />
@ -288,13 +275,13 @@
</tr>
</thead>
<tbody class="shadow-md">
{#each stockDividends as item}
{#each rawData?.history as item}
<tr class="text-gray-200 odd:bg-[#27272A]">
<td class="text-start text-sm sm:text-[1rem] whitespace-nowrap text-white font-medium border-b border-[#09090B]">
{new Date(item?.date)?.toLocaleString('en-US', { month: 'short', day: 'numeric', year: 'numeric', daySuffix: '2-digit' })}
</td>
<td class="text-end text-sm sm:text-[1rem] whitespace-nowrap text-white border-b border-[#09090B]">
${item?.adjDividend?.toFixed(2)}
${item?.adjDividend?.toFixed(3)}
</td>
<td class="text-end text-sm sm:text-[1rem] whitespace-nowrap text-white border-b border-[#09090B]">
{item?.recordDate?.length !== 0 ? new Date(item?.recordDate)?.toLocaleString('en-US', { month: 'short', day: 'numeric', year: 'numeric', daySuffix: '2-digit' }) : 'n/a'}
@ -318,9 +305,21 @@
{/if}
{:else}
<div class="flex justify-center items-center h-80">
<div class="relative">
<label class="bg-[#09090B] rounded-xl h-14 w-14 flex justify-center items-center absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2">
<span class="loading loading-spinner loading-md"></span>
</label>
</div>
</div>
{/if}
{/if}
{/if}
</div>
@ -332,7 +331,8 @@
<style>
.app {
height: 400px;

View File

@ -1,69 +0,0 @@
// lib/workers/test.ts
const sortDividendsByDate = (dividends) => {
return dividends.sort(function(a, b) {
return new Date(a?.date) - new Date(b?.date);
});
}
function plotDividend(stockDividends) {
let dateList = [];
let dividendList = [];
let growthList = [];
let copyData = structuredClone(stockDividends);
const reverseData = sortDividendsByDate(copyData);
for (let i = 0; i < reverseData?.length; i++) {
const currentDividend = reverseData[i]?.dividend;
const previousDividend = i === 0 ? 0 : reverseData[i - 1]?.dividend;
dateList.push(reverseData[i]?.date);
dividendList?.push(currentDividend?.toFixed(2));
if (currentDividend !== null && previousDividend !== null && previousDividend !== 0) {
const growthRate = (((currentDividend - previousDividend) / previousDividend) * 100 )?.toFixed(2);
growthList?.push(growthRate);
} else {
growthList?.push(0); // Pushing null if the growth calculation is not possible
}
}
return {dividendList, growthList, dateList};
}
onmessage = async (event: MessageEvent) => {
const data = event.data?.message;
const stockDividends = data?.at(0);
const eps = data?.at(1);
const currentPrice = data?.at(2);
const payoutFrequency = stockDividends?.filter(entry => entry.date.includes('2022'))?.length;
const amount = stockDividends[0]?.adjDividend;
const annualDividend = (amount * payoutFrequency)?.toFixed(2)
const dividendYield = ((annualDividend / currentPrice )*100)?.toFixed(2)
const exDividendDate = stockDividends[0]?.date
const payoutRatio = ((1 - ( eps - annualDividend)/eps)*100)?.toFixed(2)
const previousIndex = stockDividends?.findIndex(entry => entry.date.includes('2022'));
const previousAnnualDividend = stockDividends[previousIndex]?.adjDividend * payoutFrequency;
const dividendGrowth= (( (annualDividend - previousAnnualDividend) / previousAnnualDividend ) *100)?.toFixed(2);
const {dividendList, growthList, dateList} = plotDividend(stockDividends)
//Check if the last dividend is older than 12 months
const dateDistance = new Date(stockDividends?.at(0)?.date) < new Date(new Date().setFullYear(new Date().getFullYear() - 1)) ? true : false;
let finalData = { annualDividend, payoutFrequency, exDividendDate, dividendYield, dividendGrowth, payoutRatio , dateDistance, dividendList, growthList, dateList};
postMessage({ message: 'success', finalData});
// Sending data back to the main thread
//postMessage({ message: 'Data received in the worker', ticker, apiURL });
};
export {};

View File

@ -11,26 +11,36 @@ use([LineChart, BarChart, TooltipComponent, GridComponent, CanvasRenderer])
export let data;
let isLoaded = false;
let dateDistance;
let stockDividends = data?.getStockDividend?.at(0)?.filter(item => item?.recordDate && item?.paymentDate);
let rawData = data?.getStockDividend;
let optionsDividend;
let exDividendDate = 'n/a';
let dividendYield = 'n/a';
let annualDividend = 'n/a';
let payoutFrequency = 'n/a';
let payoutRatio = 'n/a';
let dividendGrowth = 'n/a';
let dividendList = [];
let dateList = [];
let exDividendDate = rawData?.history?.at(0)?.date;
let dividendYield = rawData?.dividendYield;
let annualDividend = rawData?.annualDividend;
let payoutFrequency = rawData?.payoutFrequency;
let payoutRatio = rawData?.payoutRatio;
let dividendGrowth = rawData?.dividendGrowth;
async function plotDividend(dividendList, dateList) {
async function plotDividend() {
let dates = [];
let dividendList = [];
// Iterate over the data and extract required information
rawData?.history?.forEach(item => {
dates?.push(item?.paymentDate);
dividendList?.push(item?.adjDividend);
});
dates?.sort((a,b) => new Date(a) - new Date(b));
const options = {
tooltip: {
trigger: 'axis',
@ -39,13 +49,13 @@ async function plotDividend(dividendList, dateList) {
animation: false,
grid: {
left: '2%',
right: '0%',
right: '3%',
bottom: '10%',
top: '10%',
containLabel: true
},
xAxis: {
data: dateList,
data: dates,
type: 'category',
axisLabel: {
color: '#fff',
@ -92,36 +102,10 @@ async function plotDividend(dividendList, dateList) {
let syncWorker: Worker | undefined = undefined;
// Handling messages from the worker
const handleMessage = async (event) => {
const finalData = event.data?.finalData
payoutFrequency = finalData?.payoutFrequency;
exDividendDate = finalData?.exDividendDate;
dividendYield = finalData?.dividendYield;
dividendGrowth = finalData?.dividendGrowth;
payoutRatio = finalData?.payoutRatio;
dateDistance = finalData?.dateDistance;
dividendList = finalData?.dividendList;
dateList = finalData?.dateList;
annualDividend = finalData?.annualDividend;
optionsDividend = await plotDividend(dividendList, dateList)
//console.log('Message from worker:', chartData);
};
const loadWorker = async () => {
const SyncWorker = await import('./workers/dividendWorker?worker');
syncWorker = new SyncWorker.default();
syncWorker.postMessage({ message: data?.getStockDividend});
syncWorker.onmessage = handleMessage;
};
onMount(async() => {
await loadWorker()
optionsDividend = await plotDividend()
isLoaded = true;
})
@ -153,21 +137,23 @@ onMount(async() => {
<section class="bg-[#09090B] overflow-hidden text-white h-full mb-40 sm:mb-0">
<div class="flex h-full overflow-hidden">
<div class="relative flex justify-center items-center overflow-hidden">
<section class="w-full bg-[#09090B] overflow-hidden text-white h-full mb-40 sm:mb-0">
<div class="w-full flex h-full overflow-hidden">
<div class="w-full relative flex justify-center items-center overflow-hidden">
<div class="sm:p-7 w-full m-auto mt-2 sm:mt-0">
<div class="mb-6">
<div class="w-full mb-6">
<h1 class="text-2xl sm:text-3xl text-gray-200 font-bold mb-4">
Dividends
</h1>
<div class="text-white text-start p-3 sm:p-5 mb-10 rounded-lg sm:flex sm:flex-row sm:items-center border border-slate-800 text-sm sm:text-[1rem]">
<div class="w-full text-white text-start p-3 sm:p-5 mb-10 rounded-lg sm:flex sm:flex-row sm:items-center border border-slate-800 text-sm sm:text-[1rem]">
<svg class="w-6 h-6 flex-shrink-0 inline-block sm:mr-2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256"><path fill="#a474f6" d="M128 24a104 104 0 1 0 104 104A104.11 104.11 0 0 0 128 24m-4 48a12 12 0 1 1-12 12a12 12 0 0 1 12-12m12 112a16 16 0 0 1-16-16v-40a8 8 0 0 1 0-16a16 16 0 0 1 16 16v40a8 8 0 0 1 0 16"/></svg>
{#if stockDividends?.length !== 0}
{#if rawData?.history?.length !== 0}
{#if !dateDistance}
{$displayCompanyName} has an annual dividend of
${annualDividend}
@ -179,20 +165,20 @@ onMount(async() => {
{new Date(exDividendDate)?.toLocaleString('en-US', { month: 'short', day: 'numeric', year: 'numeric', daySuffix: '2-digit' })}
{:else}
{$displayCompanyName} issued its most recent dividend on
{new Date(stockDividends?.at(0)?.date)?.toLocaleString('en-US', { month: 'short', day: 'numeric', year: 'numeric', daySuffix: '2-digit' })}.
{new Date(rawData?.history?.at(0)?.date)?.toLocaleString('en-US', { month: 'short', day: 'numeric', year: 'numeric', daySuffix: '2-digit' })}.
Since then, the company has not distributed any further dividends for over 12 months.
{/if}
{:else}
No dividend history available for {$displayCompanyName}. Likely, the stock has never paid dividends.
No dividend history available for {$displayCompanyName}.
{/if}
</div>
</div>
{#if stockDividends?.length !== 0}
{#if rawData?.history?.length !== 0}
<div class="mb-4 grid grid-cols-2 grid-rows-2 rounded-lg border border-gray-600 bg-[#272727] shadow md:grid-cols-4 md:grid-rows-1">
<div class="p-4 bp:p-5 sm:p-6">
<div class="text-sm font-normal text-default xs:text-base">
@ -261,7 +247,9 @@ onMount(async() => {
</div>
{#if stockDividends?.length !== 0 && optionsDividend}
{#if isLoaded}
{#if rawData?.history?.length !== 0 && optionsDividend}
<div class="app w-full">
<Chart {init} options={optionsDividend} class="chart" />
@ -287,7 +275,7 @@ onMount(async() => {
</tr>
</thead>
<tbody class="shadow-md">
{#each stockDividends as item}
{#each rawData?.history as item}
<tr class="text-gray-200 odd:bg-[#27272A]">
<td class="text-start text-sm sm:text-[1rem] whitespace-nowrap text-white font-medium border-b border-[#09090B]">
{new Date(item?.date)?.toLocaleString('en-US', { month: 'short', day: 'numeric', year: 'numeric', daySuffix: '2-digit' })}
@ -317,9 +305,21 @@ onMount(async() => {
{/if}
{:else}
<div class="flex justify-center items-center h-80">
<div class="relative">
<label class="bg-[#09090B] rounded-xl h-14 w-14 flex justify-center items-center absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2">
<span class="loading loading-spinner loading-md"></span>
</label>
</div>
</div>
{/if}
{/if}
{/if}
</div>

View File

@ -1,59 +0,0 @@
// lib/workers/test.ts
const sortDividendsByDate = (dividends) => {
return dividends.sort(function(a, b) {
return new Date(a?.date) - new Date(b?.date);
});
}
function plotDividend(stockDividends) {
let dateList = [];
let dividendList = [];
let growthList = [];
let copyData = structuredClone(stockDividends);
const reverseData = sortDividendsByDate(copyData);
for (let i = 0; i < reverseData?.length; i++) {
const currentDividend = reverseData[i]?.dividend;
dateList.push(reverseData[i]?.paymentDate);
dividendList?.push(currentDividend);
}
return {dividendList, growthList, dateList};
}
onmessage = async (event: MessageEvent) => {
const data = event.data?.message;
const stockDividends = data?.at(0)?.filter(item => item?.recordDate && item?.paymentDate);
const eps = data?.at(1);
const currentPrice = data?.at(2);
const payoutFrequency = stockDividends?.filter(entry => entry.date.includes('2023'))?.length;
const amount = stockDividends[0]?.adjDividend;
const annualDividend = (amount * payoutFrequency)?.toFixed(2)
const dividendYield = ((annualDividend / currentPrice )*100)?.toFixed(2)
const exDividendDate = stockDividends[0]?.date
const payoutRatio = ((1 - ( eps - annualDividend)/eps)*100)?.toFixed(2)
const previousIndex = stockDividends?.findIndex(entry => entry.date.includes('2023'));
const previousAnnualDividend = stockDividends[previousIndex]?.adjDividend * payoutFrequency;
const dividendGrowth= (( (annualDividend - previousAnnualDividend) / previousAnnualDividend ) *100)?.toFixed(2);
const {dividendList, dateList} = plotDividend(stockDividends)
//Check if the last dividend is older than 12 months
const dateDistance = new Date(stockDividends?.at(0)?.date) < new Date(new Date().setFullYear(new Date().getFullYear() - 1)) ? true : false;
let finalData = { annualDividend, payoutFrequency, exDividendDate, dividendYield, dividendGrowth, payoutRatio , dateDistance, dividendList, dateList};
postMessage({ message: 'success', finalData});
// Sending data back to the main thread
//postMessage({ message: 'Data received in the worker', ticker, apiURL });
};
export {};