From 93196954abde34cba74143ab839af0a4992f8eef Mon Sep 17 00:00:00 2001 From: MuslemRahimi Date: Sat, 7 Sep 2024 21:01:38 +0200 Subject: [PATCH] add export button --- src/routes/stocks/[tickerID]/+page.svelte | 66 +++++++++++++++++------ 1 file changed, 51 insertions(+), 15 deletions(-) diff --git a/src/routes/stocks/[tickerID]/+page.svelte b/src/routes/stocks/[tickerID]/+page.svelte index 37472123..9fb4dd9d 100644 --- a/src/routes/stocks/[tickerID]/+page.svelte +++ b/src/routes/stocks/[tickerID]/+page.svelte @@ -204,9 +204,9 @@ case "MAX": displayData = "MAX"; await historicalPrice("max"); - if (threeYearPrice?.length !== 0) { - displayLastLogicalRangeValue = threeYearPrice?.at(0)?.close; - lastValue = threeYearPrice.slice(-1)?.at(0)?.close; + if (maxPrice?.length !== 0) { + displayLastLogicalRangeValue = maxPrice?.at(0)?.close; + lastValue = maxPrice.slice(-1)?.at(0)?.close; } else { displayLastLogicalRangeValue = null; lastValue = null; @@ -236,9 +236,9 @@ let sixMonthPrice = []; let oneYearPrice = []; - let threeYearPrice = []; + let maxPrice = []; - async function historicalPrice(timePeriod: string) { +async function historicalPrice(timePeriod: string) { const cachedData = getCache($stockTicker, "historicalPrice" + timePeriod); if (cachedData) { switch (timePeriod) { @@ -255,7 +255,7 @@ oneYearPrice = cachedData; break; case "max": - threeYearPrice = cachedData; + maxPrice = cachedData; break; default: console.log(`Unsupported time period: ${timePeriod}`); @@ -304,16 +304,18 @@ oneYearPrice = mappedData; break; case "max": - threeYearPrice = mappedData; + maxPrice = mappedData; break; default: console.log(`Unsupported time period: ${timePeriod}`); } + setCache($stockTicker, mappedData, "historicalPrice" + timePeriod); } catch (e) { console.log(e); } } + } async function initializePrice() { @@ -543,7 +545,7 @@ "1M": oneMonthPrice, "6M": sixMonthPrice, "1Y": oneYearPrice, - "MAX": threeYearPrice, + "MAX": maxPrice, }; @@ -554,7 +556,7 @@ oneWeekPrice = []; oneMonthPrice = []; oneYearPrice = []; - threeYearPrice = []; + maxPrice = []; prePostData = {}; communitySentiment = {}; output = null; @@ -578,6 +580,34 @@ $globalForm = form; } } + +async function exportData() { + + await historicalPrice('max'); + + const csvRows = []; + + // Add headers row + csvRows.push('time,open,high,low,close'); + + // Add data rows + for (const row of output) { + const csvRow = `${row.time},${row.open},${row.high},${row.low},${row.close}`; + csvRows.push(csvRow); + } + + // Create CSV blob and trigger download + const csv = csvRows.join('\n'); + const blob = new Blob([csv], { type: 'text/csv' }); + const url = window.URL.createObjectURL(blob); + const a = document.createElement('a'); + a.setAttribute('hidden', ''); + a.setAttribute('href', url); + a.setAttribute('download', `${$stockTicker}.csv`); + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + } @@ -719,13 +749,20 @@
-