Update frontend components

This commit is contained in:
thecodebranch 2024-07-29 15:19:25 -04:00
parent dce8860e2e
commit 143cbfc6a8
27 changed files with 1720 additions and 0 deletions

24
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

3
frontend/.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"recommendations": ["svelte.svelte-vscode"]
}

47
frontend/README.md Normal file
View File

@ -0,0 +1,47 @@
# Svelte + Vite
This template should help get you started developing with Svelte in Vite.
## Recommended IDE Setup
[VS Code](https://code.visualstudio.com/) + [Svelte](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode).
## Need an official Svelte framework?
Check out [SvelteKit](https://github.com/sveltejs/kit#readme), which is also powered by Vite. Deploy anywhere with its serverless-first approach and adapt to various platforms, with out of the box support for TypeScript, SCSS, and Less, and easily-added support for mdsvex, GraphQL, PostCSS, Tailwind CSS, and more.
## Technical considerations
**Why use this over SvelteKit?**
- It brings its own routing solution which might not be preferable for some users.
- It is first and foremost a framework that just happens to use Vite under the hood, not a Vite app.
This template contains as little as possible to get started with Vite + Svelte, while taking into account the developer experience with regards to HMR and intellisense. It demonstrates capabilities on par with the other `create-vite` templates and is a good starting point for beginners dipping their toes into a Vite + Svelte project.
Should you later need the extended capabilities and extensibility provided by SvelteKit, the template has been structured similarly to SvelteKit so that it is easy to migrate.
**Why `global.d.ts` instead of `compilerOptions.types` inside `jsconfig.json` or `tsconfig.json`?**
Setting `compilerOptions.types` shuts out all other types not explicitly listed in the configuration. Using triple-slash references keeps the default TypeScript setting of accepting type information from the entire workspace, while also adding `svelte` and `vite/client` type information.
**Why include `.vscode/extensions.json`?**
Other templates indirectly recommend extensions via the README, but this file allows VS Code to prompt the user to install the recommended extension upon opening the project.
**Why enable `checkJs` in the JS template?**
It is likely that most cases of changing variable types in runtime are likely to be accidental, rather than deliberate. This provides advanced typechecking out of the box. Should you like to take advantage of the dynamically-typed nature of JavaScript, it is trivial to change the configuration.
**Why is HMR not preserving my local component state?**
HMR state preservation comes with a number of gotchas! It has been disabled by default in both `svelte-hmr` and `@sveltejs/vite-plugin-svelte` due to its often surprising behavior. You can read the details [here](https://github.com/sveltejs/svelte-hmr/tree/master/packages/svelte-hmr#preservation-of-local-state).
If you have state that's important to retain within a component, consider creating an external store which would not be replaced by HMR.
```js
// store.js
// An extremely simple external store
import { writable } from 'svelte/store'
export default writable(0)
```

13
frontend/index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + Svelte</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>

32
frontend/jsconfig.json Normal file
View File

@ -0,0 +1,32 @@
{
"compilerOptions": {
"moduleResolution": "bundler",
"target": "ESNext",
"module": "ESNext",
/**
* svelte-preprocess cannot figure out whether you have
* a value or a type, so tell TypeScript to enforce using
* `import type` instead of `import` for Types.
*/
"verbatimModuleSyntax": true,
"isolatedModules": true,
"resolveJsonModule": true,
/**
* To have warnings / errors of the Svelte compiler at the
* correct position, enable source maps by default.
*/
"sourceMap": true,
"esModuleInterop": true,
"skipLibCheck": true,
/**
* Typecheck JS in `.svelte` and `.js` files by default.
* Disable this if you'd like to use dynamic types.
*/
"checkJs": false
},
/**
* Use global.d.ts instead of compilerOptions.types
* to avoid limiting type declarations.
*/
"include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.svelte"]
}

22
frontend/package.json Normal file
View File

@ -0,0 +1,22 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^3.1.1",
"autoprefixer": "^10.4.19",
"postcss": "^8.4.39",
"svelte": "^4.2.18",
"tailwindcss": "^3.4.6",
"vite": "^5.3.4"
},
"dependencies": {
"chart.js": "^4.4.3"
}
}

View File

@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 159 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

1
frontend/public/vite.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

59
frontend/src/App.svelte Normal file
View File

@ -0,0 +1,59 @@
<script>
import { onMount } from "svelte";
import { selectedTicker, tickerSymbols, historicalData, indicatorData } from "./stores.js";
import { getTickers } from "./api/tickers.js";
import { getHistoricalTickerData } from "./api/historical.js";
import { getSma } from "./api/indicators.js";
import TickerSelector from "./lib/TickerSelector.svelte";
import HistoricalData from "./lib/HistoricalData.svelte";
import DateSelector from "./lib/DateSelector.svelte";
import IndicatorSelector from "./lib/IndicatorSelector.svelte";
import { get } from "svelte/store";
let historicalDataForTicker = [];
let fromDate = "2000-01-01";
let toDate = "2001-01-01";
let period = 5;
onMount(async () => {
const data = await getTickers();
tickerSymbols.set(data);
});
const handleDateChange = async (event) => {
fromDate = event.detail.fromDate;
toDate = event.detail.toDate;
handleTickerSelect(get(selectedTicker));
}
const handleTickerSelect = async (ticker) => {
selectedTicker.set(ticker);
console.log("Ticker selected:", ticker);
//const historical = await getHistoricalTickerData(ticker, fromDate, toDate);
//historicalData.set({ [ticker]: historical });
//historicalDataForTicker = historical;
const smaIndicator = await getSma(ticker, period, fromDate, toDate);
indicatorData.set({ [ticker]: smaIndicator });
};
const handlePeriodChange = async (event) => {
period = event.detail.period;
console.log("here")
handleTickerSelect(get(selectedTicker));
};
</script>
<main class="w-full h-screen flex justify-between gap-2 bg-gray-100">
<TickerSelector tickers={$tickerSymbols} onSelect={handleTickerSelect}/>
<HistoricalData sma={period}/>
<div class="flex flex-col gap-2 m-5 p-2 w-[150px] bg-gray-100 rounded text-xs">
<DateSelector on:dateChange={handleDateChange} />
<IndicatorSelector on:periodChange={handlePeriodChange} />
</div>
</main>

View File

@ -0,0 +1,14 @@
const BASE_URL = "/api/v1/historical"
export async function getHistoricalTickerData(ticker, fromDate, toDate) {
try {
const url = `${BASE_URL}/${ticker}?from_date=${fromDate}&to_date=${toDate}`;
const response = await fetch(url);
const data = await response.json();
return data.data;
} catch (error) {
console.error("Error fetching historical data: ", error);
return [];
}
}

View File

@ -0,0 +1,14 @@
const BASE_URL = "/api/v1/indicators/sma"
export async function getSma(ticker, period, fromDate, toDate) {
try {
const url = `${BASE_URL}/${ticker}?period=${period}&from_date=${fromDate}&to_date=${toDate}`;
const response = await fetch(url);
const indicator = await response.json();
return indicator.data.data;
} catch (error) {
console.error("Error fetching historical data: ", error);
return [];
}
}

View File

@ -0,0 +1,13 @@
const BASE_URL = "/api/v1/tickers"
export async function getTickers() {
try {
const response = await fetch(BASE_URL);
const tickersData = await response.json();
return tickersData.data;
} catch (error) {
console.error("Error fetching tickers data: ", error);
return [];
}
}

3
frontend/src/app.css Normal file
View File

@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="26.6" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 308"><path fill="#FF3E00" d="M239.682 40.707C211.113-.182 154.69-12.301 113.895 13.69L42.247 59.356a82.198 82.198 0 0 0-37.135 55.056a86.566 86.566 0 0 0 8.536 55.576a82.425 82.425 0 0 0-12.296 30.719a87.596 87.596 0 0 0 14.964 66.244c28.574 40.893 84.997 53.007 125.787 27.016l71.648-45.664a82.182 82.182 0 0 0 37.135-55.057a86.601 86.601 0 0 0-8.53-55.577a82.409 82.409 0 0 0 12.29-30.718a87.573 87.573 0 0 0-14.963-66.244"></path><path fill="#FFF" d="M106.889 270.841c-23.102 6.007-47.497-3.036-61.103-22.648a52.685 52.685 0 0 1-9.003-39.85a49.978 49.978 0 0 1 1.713-6.693l1.35-4.115l3.671 2.697a92.447 92.447 0 0 0 28.036 14.007l2.663.808l-.245 2.659a16.067 16.067 0 0 0 2.89 10.656a17.143 17.143 0 0 0 18.397 6.828a15.786 15.786 0 0 0 4.403-1.935l71.67-45.672a14.922 14.922 0 0 0 6.734-9.977a15.923 15.923 0 0 0-2.713-12.011a17.156 17.156 0 0 0-18.404-6.832a15.78 15.78 0 0 0-4.396 1.933l-27.35 17.434a52.298 52.298 0 0 1-14.553 6.391c-23.101 6.007-47.497-3.036-61.101-22.649a52.681 52.681 0 0 1-9.004-39.849a49.428 49.428 0 0 1 22.34-33.114l71.664-45.677a52.218 52.218 0 0 1 14.563-6.398c23.101-6.007 47.497 3.036 61.101 22.648a52.685 52.685 0 0 1 9.004 39.85a50.559 50.559 0 0 1-1.713 6.692l-1.35 4.116l-3.67-2.693a92.373 92.373 0 0 0-28.037-14.013l-2.664-.809l.246-2.658a16.099 16.099 0 0 0-2.89-10.656a17.143 17.143 0 0 0-18.398-6.828a15.786 15.786 0 0 0-4.402 1.935l-71.67 45.674a14.898 14.898 0 0 0-6.73 9.975a15.9 15.9 0 0 0 2.709 12.012a17.156 17.156 0 0 0 18.404 6.832a15.841 15.841 0 0 0 4.402-1.935l27.345-17.427a52.147 52.147 0 0 1 14.552-6.397c23.101-6.006 47.497 3.037 61.102 22.65a52.681 52.681 0 0 1 9.003 39.848a49.453 49.453 0 0 1-22.34 33.12l-71.664 45.673a52.218 52.218 0 0 1-14.563 6.398"></path></svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

View File

@ -0,0 +1,26 @@
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
let fromDate = '2001-01-01';
let toDate = '2002-01-01';
const handleSubmit = () => {
console.log(fromDate);
dispatch('dateChange', { fromDate, toDate });
};
</script>
<div class="w-full">
<label class="block mb-2">
From:
<input type="date" bind:value={fromDate} class="block w-full p-2 border rounded"/>
</label>
<label class="block mb-4">
To:
<input type="date" bind:value={toDate} class="block w-full p-2 border rounded"/>
</label>
<button on:click={handleSubmit} class="bg-gray-300 text-xs w-full text-white px-4 py-2 rounded hover:bg-gray-700">
Fetch Data
</button>
</div>

View File

@ -0,0 +1,115 @@
<!-- src/HistoricalData.svelte -->
<script>
import { selectedTicker, historicalData, indicatorData } from "../stores.js";
import { Chart } from 'chart.js/auto';
import { get } from 'svelte/store';
const smaMap = {
5: "sma_5",
10: "sma_10",
20: "sma_20",
50: "sma_50",
100: "sma_100",
200: "sma_200",
}
export let sma = 5;
let chartContainer;
let chart;
let ticker = get(selectedTicker);
let data = get(historicalData)[ticker] || [];
let indicators = get(indicatorData) || [];
// Watch the selectedTicker store for changes
$: ticker = $selectedTicker;
$: data = $historicalData[ticker] || [];
$: indicators = $indicatorData[ticker] || [];
// Log to check the state of data
$: if (indicators.length > 0) {
console.log('Rendering chart for ticker:', ticker);
renderChart(indicators);
}
function renderChart(indicators) {
if (chart) chart.destroy();
let smaKey = smaMap[sma];
const labels = indicators.map(item => item.date);
const closePrices = indicators.map(item => item.close);
const indicatorValues = indicators.map(item => item[smaKey]);
const ctx = chartContainer.getContext("2d");
chart = new Chart(ctx, {
type: "line",
data: {
labels: labels,
datasets: [
{
label: "Close Price",
data: closePrices,
borderColor: "rgba(75, 192, 192, 1)",
borderWidth: 1,
fill: false
},
{
label: "Indicator",
data: indicatorValues,
borderColor: "rgba(255, 99, 132, 1)",
borderWidth: 1,
fill: false
}
]
},
options: {
animation: false,
scales: {
x: {
title: {
display: true,
text: 'Closing Date',
font: {
family: 'Arial',
size: 14,
weight: 'bold',
lineHeight: 1.2
},
},
ticks: {
maxTicksLimit: 10
}
},
y: {
title: {
display: true,
text: 'Closing Price',
font: {
family: 'Arial',
size: 14,
weight: 'bold',
lineHeight: 1.2
},
},
beginAtZero: false,
}
}
}
});
}
</script>
<div class="w-3/4 h-4/5 pb-5 m-auto rounded-lg flex flex-col align-center justify-center bg-white shadow-lg">
{#if ticker}
<div class="p-2 bg-gray-500 text-md text-white">
{ ticker }
</div>
{#if data}
<canvas bind:this={chartContainer} class="m-auto w-full p-5"></canvas>
{/if}
{:else}
<img src="/chart-loader-2.png" alt="Chart Loading Picture." class="w-full h-full object-cover rounded-md"/>
{/if}
</div>

View File

@ -0,0 +1,23 @@
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
let selectedPeriod = 5;
const periods = [5, 10, 20, 50, 100, 200];
const handlePeriodChange = () => {
dispatch('periodChange', { period: selectedPeriod });
};
</script>
<div class="bg-gray-100 rounded text-xs">
<label class="block mb-2">
SMA Window:
<select bind:value={selectedPeriod} on:change={handlePeriodChange} class="block w-full p-2 border rounded">
{#each periods as period}
<option value={period}>{period}</option>
{/each}
</select>
</label>
</div>

View File

@ -0,0 +1,21 @@
<script>
import { createEventDispatcher } from "svelte";
export let tickers;
export let onSelect;
const dispatch = createEventDispatcher();
const selectTicker = (ticker) => {
onSelect(ticker);
};
</script>
<div class="w-[150px] flex-col flex gap-1 m-5 p-1 overflow-y-scroll">
{#each tickers as ticker}
<div class="rounded p-2 bg-gray-400 text-xs text-center text-white hover:cursor-pointer hover:bg-gray-600" on:click={() => selectTicker(ticker)}>
{ ticker }
</div>
{/each}
</div>

8
frontend/src/main.js Normal file
View File

@ -0,0 +1,8 @@
import './app.css'
import App from './App.svelte'
const app = new App({
target: document.getElementById('app'),
})
export default app

7
frontend/src/stores.js Normal file
View File

@ -0,0 +1,7 @@
import { writable } from "svelte/store";
export const tickerSymbols = writable([]);
export const historicalData = writable({});
export const selectedTicker = writable(null);
export const indicatorData = writable({});

2
frontend/src/vite-env.d.ts vendored Normal file
View File

@ -0,0 +1,2 @@
/// <reference types="svelte" />
/// <reference types="vite/client" />

View File

@ -0,0 +1,7 @@
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'
export default {
// Consult https://svelte.dev/docs#compile-time-svelte-preprocess
// for more information about preprocessors
preprocess: vitePreprocess(),
}

View File

@ -0,0 +1,10 @@
export default {
content: [
"./index.html",
"./src/**/*.{svelte,js,ts}",
],
theme: {
extend: {},
},
plugins: [],
}

15
frontend/vite.config.js Normal file
View File

@ -0,0 +1,15 @@
import { defineConfig } from "vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";
export default defineConfig({
plugins: [svelte()],
server: {
proxy: {
"/api": {
target: "http://localhost:3000",
changeOrigin: true,
}
}
}
});

1234
frontend/yarn.lock Normal file

File diff suppressed because it is too large Load Diff