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'>
import {screenWidth} from '$lib/store';
import {stockTicker, screenWidth, userRegion, getCache, setCache} from '$lib/store';
import InfoModal from '$lib/components/InfoModal.svelte';
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';
export let analystEstimateList;
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 dataset = [];
@ -51,78 +65,124 @@ const padding = 2.5;
let tableDataActual = [];
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
$: {
if (displayData && analystEstimateList?.length !== 0)
{
function prepareData(analystEstimateList) {
dataset = [];
tableDataActual = [];
tableDataForecast = [];
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);
displayRevenueUnit = unit;
const { unit, denominator } = determineDisplayUnit(analystEstimateList?.at(-1)?.estimatedRevenueAvg);
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)});
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' });
});
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)});
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);
displayNetIncomeUnit = unit;
else if(displayData === 'Net Income') {
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) {
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' });
});
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)});
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') {
analystEstimateList?.slice(-7)?.forEach(item => {
else if(displayData === 'EPS') {
analystEstimateList?.slice(-7)?.forEach(item => {
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)});
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?.estimatedEpsAvg !== null ? item?.estimatedEpsAvg : null, 'dataset': 'forecast' });
});
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)});
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?.estimatedEpsAvg !== null ? item?.estimatedEpsAvg : null, 'dataset': 'forecast' });
});
}
else if(displayData === 'EBITDA') {
const { unit, denominator } = determineDisplayUnit(analystEstimateList?.at(-1)?.estimatedEbitdaAvg);
displayEBITDAUnit = unit;
else if(displayData === 'EBITDA') {
const { unit, denominator } = determineDisplayUnit(analystEstimateList?.at(-1)?.estimatedEbitdaAvg);
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)});
tableDataForecast?.push({ 'FY': Number(String(item?.date)?.slice(-2)), 'val': (item?.estimatedEbitdaAvg/ 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)});
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?.estimatedEbitdaAvg !== null ? (item?.estimatedEbitdaAvg / denominator)?.toFixed(2) : null, 'dataset': 'forecast' });
});
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?.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>
<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">
<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>
<InfoModal
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.`}
id={"predictiveFundamentalsInfo"}
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.`}
id={"predictiveFundamentalsInfo"}
/>
</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">
We analyze insights from various analysts to offer both historical and future fundamental data forecasts.
</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}>
@ -283,6 +343,16 @@ $: {
</h2>
{/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>
</main>
</div>

View File

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

View File

@ -5,7 +5,6 @@
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 { onDestroy, onMount } from 'svelte';
import AnalystEstimate from '$lib/components/AnalystEstimate.svelte';
import StockKeyInformation from '$lib/components/StockKeyInformation.svelte';
import BullBearSay from '$lib/components/BullBearSay.svelte';
import CommunitySentiment from '$lib/components/CommunitySentiment.svelte';
@ -31,7 +30,6 @@
let pricePrediction = data?.getPricePrediction ?? [];
let stockDeck = data?.getStockDeck ?? [];
let analystEstimateList = data?.getAnalystEstimate ?? []
let fairPrice = data?.getFairPrice ?? [];
let correlationList = data?.getCorrelation?.correlation ?? [];
let modelStats = data?.getTradingSignals ?? {};
@ -73,7 +71,6 @@
//let StockKeyInformation;
//let AnalystEstimate;
@ -641,7 +638,6 @@ function changeChartType() {
modelStats = data?.getTradingSignals;
stockDeck = data?.getStockDeck;
correlationList = data?.getCorrelation?.correlation;
analystEstimateList = data?.getAnalystEstimate;
previousClose = data?.getStockQuote?.previousClose;
marketMoods = data?.getBullBearSay;
taRating = data?.getStockTARating;
@ -1242,13 +1238,14 @@ function changeChartType() {
{/if}
<div class="w-full m-auto sm:pl-6 sm:pb-6 sm:pt-6 {analystEstimateList?.length !== 0 ? '' : 'hidden'}">
{#if AnalystEstimate}
<AnalystEstimate data={data} analystEstimateList={analystEstimateList}/>
{/if}
<Lazy>
<div class="w-full m-auto sm:pl-6 sm:pb-6 sm:pt-6">
{#await import('$lib/components/AnalystEstimate.svelte') then {default: Comp}}
<svelte:component this={Comp} data={data}/>
{/await}
</div>
</Lazy>
<Lazy>