add lazy loading to AnalystEstimate component

This commit is contained in:
MuslemRahimi 2024-06-07 10:28:42 +02:00
parent f759268c22
commit 1a3d5a86e1
3 changed files with 139 additions and 75 deletions

View File

@ -1,5 +1,5 @@
<script lang='ts'> <script lang='ts'>
import {screenWidth} from '$lib/store'; import {stockTicker, screenWidth, userRegion, getCache, setCache} from '$lib/store';
import InfoModal from '$lib/components/InfoModal.svelte'; import InfoModal from '$lib/components/InfoModal.svelte';
import { LayerCake, Html } from 'layercake'; import { LayerCake, Html } from 'layercake';
@ -9,9 +9,23 @@ import AxisX from '$lib/components/Scatter//AxisX.html.svelte';
import AxisY from '$lib/components/Scatter//AxisY.html.svelte'; import AxisY from '$lib/components/Scatter//AxisY.html.svelte';
export let analystEstimateList;
export let data; export let data;
let analystEstimateList = [];
let isLoaded = false;
const usRegion = ['cle1','iad1','pdx1','sfo1'];
let apiURL;
userRegion.subscribe(value => {
if (usRegion.includes(value)) {
apiURL = import.meta.env.VITE_USEAST_API_URL;
} else {
apiURL = import.meta.env.VITE_EU_API_URL;
}
});
let deactivateContent = data?.user?.tier === 'Pro' ? false : true; let deactivateContent = data?.user?.tier === 'Pro' ? false : true;
let dataset = []; let dataset = [];
@ -51,78 +65,124 @@ const padding = 2.5;
let tableDataActual = []; let tableDataActual = [];
let tableDataForecast = [] let tableDataForecast = []
const getAnalystEstimate = async (ticker) => {
// Get cached data for the specific tickerID
const cachedData = getCache(ticker, 'getAnalystEstimate');
if (cachedData) {
analystEstimateList = cachedData;
} else {
const postData = {'ticker': ticker};
// make the POST request to the endpoint
const response = await fetch(apiURL + '/analyst-estimate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postData)
});
analystEstimateList = await response?.json();
// Cache the data for this specific tickerID with a specific name 'getAnalystEstimate'
setCache(ticker, analystEstimateList, 'getAnalystEstimate');
}
};
//To-do: Optimize this piece of shit //To-do: Optimize this piece of shit
$: { function prepareData(analystEstimateList) {
if (displayData && analystEstimateList?.length !== 0)
{
dataset = []; dataset = [];
tableDataActual = []; tableDataActual = [];
tableDataForecast = []; tableDataForecast = [];
xData = analystEstimateList?.slice(-7)?.map(({ date }) => Number(String(date)?.slice(-2))); xData = analystEstimateList?.slice(-7)?.map(({ date }) => Number(String(date)?.slice(-2)));
if(displayData === 'Revenue') { if(displayData === 'Revenue') {
const { unit, denominator } = determineDisplayUnit(analystEstimateList?.at(-1)?.estimatedRevenueAvg); const { unit, denominator } = determineDisplayUnit(analystEstimateList?.at(-1)?.estimatedRevenueAvg);
displayRevenueUnit = unit; displayRevenueUnit = unit;
analystEstimateList?.slice(-7)?.forEach(item => { analystEstimateList?.slice(-7)?.forEach(item => {
tableDataActual?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': (item?.revenue/ denominator)?.toFixed(2)}); tableDataActual?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': (item?.revenue/ denominator)?.toFixed(2)});
tableDataForecast?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': (item?.estimatedRevenueAvg/denominator)?.toFixed(2)}); tableDataForecast?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': (item?.estimatedRevenueAvg/denominator)?.toFixed(2)});
if (item?.revenue !== null) {
dataset?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': (item?.revenue/denominator)?.toFixed(2), 'dataset': 'actual' });
}
dataset?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': item?.estimatedRevenueAvg !== null ? (item?.estimatedRevenueAvg / denominator)?.toFixed(2) : null, 'dataset': 'forecast' });
});
if (item?.revenue !== null) {
dataset?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': (item?.revenue/denominator)?.toFixed(2), 'dataset': 'actual' });
} }
dataset?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': item?.estimatedRevenueAvg !== null ? (item?.estimatedRevenueAvg / denominator)?.toFixed(2) : null, 'dataset': 'forecast' });
});
else if(displayData === 'Net Income') { }
const { unit, denominator } = analystEstimateList?.at(-2)?.estimatedNetIncomeAvg !== 0 ? determineDisplayUnit(analystEstimateList?.at(-2)?.estimatedNetIncomeAvg) : determineDisplayUnit(analystEstimateList?.at(-1)?.netIncome); else if(displayData === 'Net Income') {
displayNetIncomeUnit = unit;
analystEstimateList?.slice(-7)?.forEach(item => { const { unit, denominator } = analystEstimateList?.at(-2)?.estimatedNetIncomeAvg !== 0 ? determineDisplayUnit(analystEstimateList?.at(-2)?.estimatedNetIncomeAvg) : determineDisplayUnit(analystEstimateList?.at(-1)?.netIncome);
displayNetIncomeUnit = unit;
tableDataActual?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': (item?.netIncome / denominator)?.toFixed(2)});
tableDataForecast?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': (item?.estimatedNetIncomeAvg / denominator)?.toFixed(2)}); analystEstimateList?.slice(-7)?.forEach(item => {
if (item?.netIncome !== null) { tableDataActual?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': (item?.netIncome / denominator)?.toFixed(2)});
dataset?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': (item?.netIncome / denominator)?.toFixed(2), 'dataset': 'actual' }); tableDataForecast?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': (item?.estimatedNetIncomeAvg / denominator)?.toFixed(2)});
}
dataset?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': item?.estimatedNetIncomeAvg !== null ? (item?.estimatedNetIncomeAvg / denominator)?.toFixed(2) : null, 'dataset': 'forecast' }); if (item?.netIncome !== null) {
}); dataset?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': (item?.netIncome / denominator)?.toFixed(2), 'dataset': 'actual' });
} }
dataset?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': item?.estimatedNetIncomeAvg !== null ? (item?.estimatedNetIncomeAvg / denominator)?.toFixed(2) : null, 'dataset': 'forecast' });
});
}
else if(displayData === 'EPS') { else if(displayData === 'EPS') {
analystEstimateList?.slice(-7)?.forEach(item => { analystEstimateList?.slice(-7)?.forEach(item => {
tableDataActual?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': item?.eps?.toFixed(2) ?? null}); tableDataActual?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': item?.eps?.toFixed(2) ?? null});
tableDataForecast?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': item?.estimatedEpsAvg?.toFixed(2)}); tableDataForecast?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': item?.estimatedEpsAvg?.toFixed(2)});
if (item?.eps !== null) { if (item?.eps !== null) {
dataset?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': item?.eps, 'dataset': 'actual' }); dataset?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': item?.eps, 'dataset': 'actual' });
}
dataset?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': item?.estimatedEpsAvg !== null ? item?.estimatedEpsAvg : null, 'dataset': 'forecast' });
});
} }
dataset?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': item?.estimatedEpsAvg !== null ? item?.estimatedEpsAvg : null, 'dataset': 'forecast' });
});
}
else if(displayData === 'EBITDA') { else if(displayData === 'EBITDA') {
const { unit, denominator } = determineDisplayUnit(analystEstimateList?.at(-1)?.estimatedEbitdaAvg); const { unit, denominator } = determineDisplayUnit(analystEstimateList?.at(-1)?.estimatedEbitdaAvg);
displayEBITDAUnit = unit; displayEBITDAUnit = unit;
analystEstimateList?.slice(-7)?.forEach(item => { analystEstimateList?.slice(-7)?.forEach(item => {
tableDataActual?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': (item?.ebitda/ denominator)?.toFixed(2)}); tableDataActual?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': (item?.ebitda/ denominator)?.toFixed(2)});
tableDataForecast?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': (item?.estimatedEbitdaAvg/ denominator)?.toFixed(2)}); tableDataForecast?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': (item?.estimatedEbitdaAvg/ denominator)?.toFixed(2)});
if (item?.ebitda !== null) { if (item?.ebitda !== null) {
dataset?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': (item?.ebitda / denominator)?.toFixed(2), 'dataset': 'actual' }); dataset?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': (item?.ebitda / denominator)?.toFixed(2), 'dataset': 'actual' });
}
dataset?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': item?.estimatedEbitdaAvg !== null ? (item?.estimatedEbitdaAvg / denominator)?.toFixed(2) : null, 'dataset': 'forecast' });
});
} }
dataset?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': item?.estimatedEbitdaAvg !== null ? (item?.estimatedEbitdaAvg / denominator)?.toFixed(2) : null, 'dataset': 'forecast' });
});
}
}
$: {
if ($stockTicker && displayData && typeof window !== 'undefined')
{
isLoaded = false;
const asyncFunctions = [
getAnalystEstimate($stockTicker)
];
Promise.all(asyncFunctions)
.then((results) => {
prepareData(analystEstimateList)
})
.catch((error) => {
console.error('An error occurred:', error);
});
isLoaded = true;
} }
@ -141,17 +201,14 @@ $: {
<main> <main>
<div class="w-fit sm:w-full sm:max-w-2xl m-auto mt-5 sm:mt-0"> <div class="w-fit sm:w-full sm:max-w-2xl m-auto mt-5 sm:mt-0">
{#if analystEstimateList?.length !== 0}
<div class="flex flex-row items-center"> <div class="flex flex-row items-center">
<label for="predictiveFundamentalsInfo" class="mr-1 cursor-pointer flex flex-row items-center text-white text-xl sm:text-3xl font-bold"> <label for="predictiveFundamentalsInfo" class="mr-1 cursor-pointer flex flex-row items-center text-white text-xl sm:text-3xl font-bold">
Predictive Fundamentals Predictive Fundamentals
</label> </label>
<InfoModal <InfoModal
title={"Predictive Fundamentals"} title={"Predictive Fundamentals"}
content={`If quarterly earnings for a year are incomplete, we offer a summarized view based on available data. For instance, if the Q4 report is missing, we display revenue as X, reflecting the sum of Q1-Q3 only. Q4 data will be added later when available.`} content={`If quarterly earnings for a year are incomplete, we offer a summarized view based on available data. For instance, if the Q4 report is missing, we display revenue as X, reflecting the sum of Q1-Q3 only. Q4 data will be added later when available.`}
id={"predictiveFundamentalsInfo"} id={"predictiveFundamentalsInfo"}
/> />
</div> </div>
@ -159,6 +216,9 @@ $: {
<div class="text-white text-sm sm:text-[1rem] mt-1 sm:mt-3 mb-1 w-full sm:w-5/6"> <div class="text-white text-sm sm:text-[1rem] mt-1 sm:mt-3 mb-1 w-full sm:w-5/6">
We analyze insights from various analysts to offer both historical and future fundamental data forecasts. We analyze insights from various analysts to offer both historical and future fundamental data forecasts.
</div> </div>
{#if isLoaded}
{#if analystEstimateList?.length !== 0}
<select class="mt-5 mb-5 sm:mb-0 sm:mt-3 ml-1 w-44 select select-bordered select-sm p-0 pl-5 overflow-y-auto bg-[#2A303C]" on:change={changeStatement}> <select class="mt-5 mb-5 sm:mb-0 sm:mt-3 ml-1 w-44 select select-bordered select-sm p-0 pl-5 overflow-y-auto bg-[#2A303C]" on:change={changeStatement}>
@ -282,7 +342,17 @@ $: {
<svg class="w-10 sm:w-12 inline-block" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="#334155" d="M18.68 12.32a4.49 4.49 0 0 0-6.36.01a4.49 4.49 0 0 0 0 6.36a4.508 4.508 0 0 0 5.57.63L21 22.39L22.39 21l-3.09-3.11c1.13-1.77.87-4.09-.62-5.57m-1.41 4.95c-.98.98-2.56.97-3.54 0c-.97-.98-.97-2.56.01-3.54c.97-.97 2.55-.97 3.53 0c.97.98.97 2.56 0 3.54M10.9 20.1a6.527 6.527 0 0 1-1.48-2.32C6.27 17.25 4 15.76 4 14v3c0 2.21 3.58 4 8 4c-.4-.26-.77-.56-1.1-.9M4 9v3c0 1.68 2.07 3.12 5 3.7v-.2c0-.93.2-1.85.58-2.69C6.34 12.3 4 10.79 4 9m8-6C7.58 3 4 4.79 4 7c0 2 3 3.68 6.85 4h.05c1.2-1.26 2.86-2 4.6-2c.91 0 1.81.19 2.64.56A3.215 3.215 0 0 0 20 7c0-2.21-3.58-4-8-4Z"/></svg> <svg class="w-10 sm:w-12 inline-block" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="#334155" d="M18.68 12.32a4.49 4.49 0 0 0-6.36.01a4.49 4.49 0 0 0 0 6.36a4.508 4.508 0 0 0 5.57.63L21 22.39L22.39 21l-3.09-3.11c1.13-1.77.87-4.09-.62-5.57m-1.41 4.95c-.98.98-2.56.97-3.54 0c-.97-.98-.97-2.56.01-3.54c.97-.97 2.55-.97 3.53 0c.97.98.97 2.56 0 3.54M10.9 20.1a6.527 6.527 0 0 1-1.48-2.32C6.27 17.25 4 15.76 4 14v3c0 2.21 3.58 4 8 4c-.4-.26-.77-.56-1.1-.9M4 9v3c0 1.68 2.07 3.12 5 3.7v-.2c0-.93.2-1.85.58-2.69C6.34 12.3 4 10.79 4 9m8-6C7.58 3 4 4.79 4 7c0 2 3 3.68 6.85 4h.05c1.2-1.26 2.86-2 4.6-2c.91 0 1.81.19 2.64.56A3.215 3.215 0 0 0 20 7c0-2.21-3.58-4-8-4Z"/></svg>
</h2> </h2>
{/if} {/if}
{:else}
<div class="flex justify-center items-center h-80">
<div class="relative">
<label class="bg-[#202020] 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}
</div> </div>
</main> </main>
</div> </div>

View File

@ -142,7 +142,6 @@ export const load = async ({ params, locals, cookies}) => {
fetchData(apiURL,'/stockdeck',params.tickerID), fetchData(apiURL,'/stockdeck',params.tickerID),
fetchData(apiURL,'/stock-correlation',params.tickerID), fetchData(apiURL,'/stock-correlation',params.tickerID),
fetchData(apiURL,'/analyst-summary-rating',params.tickerID), fetchData(apiURL,'/analyst-summary-rating',params.tickerID),
fetchData(apiURL,'/analyst-estimate',params.tickerID),
fetchData(apiURL,'/stock-quote',params.tickerID), fetchData(apiURL,'/stock-quote',params.tickerID),
fetchData(apiURL,'/stock-rating',params.tickerID), fetchData(apiURL,'/stock-rating',params.tickerID),
fetchData(apiURL,'/options-bubble',params.tickerID), fetchData(apiURL,'/options-bubble',params.tickerID),
@ -167,7 +166,6 @@ export const load = async ({ params, locals, cookies}) => {
getStockDeck, getStockDeck,
getCorrelation, getCorrelation,
getAnalystRating, getAnalystRating,
getAnalystEstimate,
getStockQuote, getStockQuote,
getStockTARating, getStockTARating,
getOptionsData, getOptionsData,
@ -198,7 +196,6 @@ export const load = async ({ params, locals, cookies}) => {
getStockDeck, getStockDeck,
getCorrelation, getCorrelation,
getAnalystRating, getAnalystRating,
getAnalystEstimate,
getStockQuote, getStockQuote,
getStockTARating, getStockTARating,
getOptionsData, getOptionsData,

View File

@ -5,7 +5,6 @@
import { TrackingModeExitMode } from 'lightweight-charts'; import { TrackingModeExitMode } from 'lightweight-charts';
import {screenWidth, displayCompanyName, numberOfUnreadNotification, globalForm, userRegion, isCrosshairMoveActive, realtimePrice, priceIncrease, currentPortfolioPrice, currentPrice, clientSideCache, stockTicker, isOpen, isBeforeMarketOpen, isWeekend} from '$lib/store'; import {screenWidth, displayCompanyName, numberOfUnreadNotification, globalForm, userRegion, isCrosshairMoveActive, realtimePrice, priceIncrease, currentPortfolioPrice, currentPrice, clientSideCache, stockTicker, isOpen, isBeforeMarketOpen, isWeekend} from '$lib/store';
import { onDestroy, onMount } from 'svelte'; import { onDestroy, onMount } from 'svelte';
import AnalystEstimate from '$lib/components/AnalystEstimate.svelte';
import StockKeyInformation from '$lib/components/StockKeyInformation.svelte'; import StockKeyInformation from '$lib/components/StockKeyInformation.svelte';
import BullBearSay from '$lib/components/BullBearSay.svelte'; import BullBearSay from '$lib/components/BullBearSay.svelte';
import CommunitySentiment from '$lib/components/CommunitySentiment.svelte'; import CommunitySentiment from '$lib/components/CommunitySentiment.svelte';
@ -31,7 +30,6 @@
let pricePrediction = data?.getPricePrediction ?? []; let pricePrediction = data?.getPricePrediction ?? [];
let stockDeck = data?.getStockDeck ?? []; let stockDeck = data?.getStockDeck ?? [];
let analystEstimateList = data?.getAnalystEstimate ?? []
let fairPrice = data?.getFairPrice ?? []; let fairPrice = data?.getFairPrice ?? [];
let correlationList = data?.getCorrelation?.correlation ?? []; let correlationList = data?.getCorrelation?.correlation ?? [];
let modelStats = data?.getTradingSignals ?? {}; let modelStats = data?.getTradingSignals ?? {};
@ -73,7 +71,6 @@
//let StockKeyInformation; //let StockKeyInformation;
//let AnalystEstimate;
@ -641,7 +638,6 @@ function changeChartType() {
modelStats = data?.getTradingSignals; modelStats = data?.getTradingSignals;
stockDeck = data?.getStockDeck; stockDeck = data?.getStockDeck;
correlationList = data?.getCorrelation?.correlation; correlationList = data?.getCorrelation?.correlation;
analystEstimateList = data?.getAnalystEstimate;
previousClose = data?.getStockQuote?.previousClose; previousClose = data?.getStockQuote?.previousClose;
marketMoods = data?.getBullBearSay; marketMoods = data?.getBullBearSay;
taRating = data?.getStockTARating; taRating = data?.getStockTARating;
@ -1241,14 +1237,15 @@ function changeChartType() {
</div> </div>
{/if} {/if}
<div class="w-full m-auto sm:pl-6 sm:pb-6 sm:pt-6 {analystEstimateList?.length !== 0 ? '' : 'hidden'}">
<Lazy>
{#if AnalystEstimate} <div class="w-full m-auto sm:pl-6 sm:pb-6 sm:pt-6">
<AnalystEstimate data={data} analystEstimateList={analystEstimateList}/> {#await import('$lib/components/AnalystEstimate.svelte') then {default: Comp}}
{/if} <svelte:component this={Comp} data={data}/>
{/await}
</div> </div>
</Lazy>
<Lazy> <Lazy>