-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquant_webapp.cpp
More file actions
358 lines (318 loc) · 13.2 KB
/
quant_webapp.cpp
File metadata and controls
358 lines (318 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
#include <iostream>
#include <vector>
#include <random>
#include <numeric>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <tuple>
#include <thread>
#include <nlohmann/json.hpp>
#include "Crow/include/crow.h"
#include "indicators.hpp"
using json = nlohmann::json;
int main() {
crow::SimpleApp app;
// Generate data once at startup
std::vector<double> dates, closes;
generateFinancialData(dates, closes, 400, 42);
// API endpoint: Get chart data with parameters
CROW_ROUTE(app, "/api/data")
.methods("GET"_method)
([&](const crow::request& req) {
// Get query parameters
auto days_param = req.url_params.get("days");
auto rsi_param = req.url_params.get("rsi");
int days = days_param ? std::stoi(days_param) : 400;
int rsi_period = rsi_param ? std::stoi(rsi_param) : 14;
// Clamp values
days = std::max(50, std::min(1000, days));
rsi_period = std::max(5, std::min(50, rsi_period));
// Generate data if days changed
std::vector<double> current_dates, current_closes;
generateFinancialData(current_dates, current_closes, days, 42);
// Calculate indicators
auto sma20 = calculateSMA(current_closes, 20);
auto sma50 = calculateSMA(current_closes, 50);
auto rsi = calculateRSI(current_closes, rsi_period);
auto [macdLine, signalLine, histogram] = calculateMACD(current_closes);
json response;
response["dates"] = current_dates;
response["closes"] = current_closes;
response["sma20"] = sma20;
response["sma50"] = sma50;
response["rsi"] = rsi;
response["macdLine"] = macdLine;
response["signalLine"] = signalLine;
response["histogram"] = histogram;
response["days"] = days;
response["rsi_period"] = rsi_period;
auto res = crow::response{response.dump()};
res.add_header("Content-Type", "application/json");
return res;
});
// API endpoint: Get statistics
CROW_ROUTE(app, "/api/stats")
.methods("GET"_method)
([&](const crow::request& req) {
auto days_param = req.url_params.get("days");
int days = days_param ? std::stoi(days_param) : 400;
days = std::max(50, std::min(1000, days));
auto rsi_param = req.url_params.get("rsi");
int rsi_period = rsi_param ? std::stoi(rsi_param) : 14;
rsi_period = std::max(5, std::min(50, rsi_period));
std::vector<double> current_dates, current_closes;
generateFinancialData(current_dates, current_closes, days, 42);
auto sma20 = calculateSMA(current_closes, 20);
auto rsi = calculateRSI(current_closes, rsi_period);
double currentPrice = current_closes.back();
double minPrice = *std::min_element(current_closes.begin(), current_closes.end());
double maxPrice = *std::max_element(current_closes.begin(), current_closes.end());
double avgPrice = std::accumulate(current_closes.begin(), current_closes.end(), 0.0) / current_closes.size();
double priceChange = current_closes.back() - current_closes.front();
double changePercent = (priceChange / current_closes.front()) * 100;
double currentRSI = rsi.back();
double currentSMA20 = sma20.back();
json stats;
stats["currentPrice"] = currentPrice;
stats["minPrice"] = minPrice;
stats["maxPrice"] = maxPrice;
stats["avgPrice"] = avgPrice;
stats["priceChange"] = priceChange;
stats["changePercent"] = changePercent;
stats["currentRSI"] = currentRSI;
stats["currentSMA20"] = currentSMA20;
stats["rsiStatus"] = currentRSI > 70 ? "OVERBOUGHT" : (currentRSI < 30 ? "OVERSOLD" : "NEUTRAL");
auto res = crow::response{stats.dump()};
res.add_header("Content-Type", "application/json");
return res;
});
// Serve HTML
CROW_ROUTE(app, "/")
([]() {
return crow::response(R"(
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quant Dashboard</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: #1a1a2e;
color: #fff;
padding: 20px;
}
.container { max-width: 1200px; margin: 0 auto; }
h1 { text-align: center; margin-bottom: 20px; color: #00d4ff; }
.controls {
background: #16213e;
padding: 20px;
border-radius: 8px;
margin-bottom: 20px;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
.control-group { display: flex; flex-direction: column; }
.control-group label { margin-bottom: 8px; font-weight: bold; color: #00d4ff; }
.control-group input {
padding: 10px;
border: 2px solid #0f3460;
background: #0f3460;
color: #fff;
border-radius: 4px;
font-size: 14px;
}
.control-group input:focus { outline: none; border-color: #00d4ff; }
.range-value { color: #00d4ff; font-weight: bold; }
.stats {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 15px;
margin-bottom: 20px;
}
.stat-card {
background: #0f3460;
padding: 15px;
border-radius: 8px;
border-left: 4px solid #00d4ff;
text-align: center;
}
.stat-label { font-size: 12px; color: #888; text-transform: uppercase; }
.stat-value { font-size: 18px; font-weight: bold; color: #00d4ff; margin-top: 5px; }
.charts {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
gap: 20px;
}
.chart-container {
background: #16213e;
padding: 20px;
border-radius: 8px;
border: 1px solid #0f3460;
}
.chart-title { color: #00d4ff; margin-bottom: 15px; font-weight: bold; }
canvas { max-height: 350px; }
.loading { text-align: center; padding: 40px; }
</style>
</head>
<body>
<div class="container">
<h1>📈 Quantitative Finance Dashboard</h1>
<div class="controls">
<div class="control-group">
<label>Trading Days: <span class="range-value" id="daysValue">400</span></label>
<input type="range" id="daysSlider" min="50" max="1000" value="400" step="50">
</div>
<div class="control-group">
<label>RSI Period: <span class="range-value" id="rsiValue">14</span></label>
<input type="range" id="rsiSlider" min="5" max="50" value="14" step="1">
</div>
</div>
<div class="stats" id="statsContainer"></div>
<div class="charts">
<div class="chart-container">
<div class="chart-title">Price & Moving Averages</div>
<canvas id="priceChart"></canvas>
</div>
<div class="chart-container">
<div class="chart-title">RSI Indicator</div>
<canvas id="rsiChart"></canvas>
</div>
<div class="chart-container">
<div class="chart-title">MACD</div>
<canvas id="macdChart"></canvas>
</div>
</div>
</div>
<script>
let charts = {};
// Debounce function for slider changes
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func(...args), delay);
};
}
async function updateCharts() {
const days = document.getElementById('daysSlider').value;
const rsi = document.getElementById('rsiSlider').value;
document.getElementById('daysValue').textContent = days;
document.getElementById('rsiValue').textContent = rsi;
try {
const [dataRes, statsRes] = await Promise.all([
fetch(`/api/data?days=${days}&rsi=${rsi}`),
fetch(`/api/stats?days=${days}&rsi=${rsi}`)
]);
const data = await dataRes.json();
const stats = await statsRes.json();
renderCharts(data);
renderStats(stats);
} catch (error) {
console.error('Error:', error);
}
}
function renderCharts(data) {
const chartConfig = {
responsive: true,
maintainAspectRatio: true,
plugins: { legend: { position: 'top' } },
scales: { x: { display: false } }
};
// Destroy existing charts
Object.values(charts).forEach(chart => chart.destroy());
// Price Chart
charts.price = new Chart(document.getElementById('priceChart'), {
type: 'line',
data: {
labels: data.dates,
datasets: [
{ label: 'Price', data: data.closes, borderColor: '#00d4ff', fill: false, borderWidth: 2, pointRadius: 0 },
{ label: 'SMA 20', data: data.sma20, borderColor: '#ff9500', borderDash: [5,5], fill: false, borderWidth: 1, pointRadius: 0 },
{ label: 'SMA 50', data: data.sma50, borderColor: '#ff1744', borderDash: [5,5], fill: false, borderWidth: 1, pointRadius: 0 }
]
},
options: chartConfig
});
// RSI Chart
charts.rsi = new Chart(document.getElementById('rsiChart'), {
type: 'line',
data: {
labels: data.dates,
datasets: [
{ label: 'RSI', data: data.rsi, borderColor: '#00d4ff', fill: false, borderWidth: 2, pointRadius: 0 }
]
},
options: {
...chartConfig,
scales: { y: { min: 0, max: 100 } }
}
});
// MACD Chart
charts.macd = new Chart(document.getElementById('macdChart'), {
type: 'line',
data: {
labels: data.dates,
datasets: [
{ label: 'MACD', data: data.macdLine, borderColor: '#00d4ff', fill: false, borderWidth: 2, pointRadius: 0 },
{ label: 'Signal', data: data.signalLine, borderColor: '#ff9500', fill: false, borderWidth: 2, pointRadius: 0 },
{ label: 'Histogram', data: data.histogram, type: 'bar', backgroundColor: 'rgba(0, 212, 255, 0.2)', borderWidth: 0 }
]
},
options: chartConfig
});
}
function renderStats(stats) {
const statContainer = document.getElementById('statsContainer');
const format = (n) => typeof n === 'number' ? n.toFixed(2) : n;
statContainer.innerHTML = `
<div class="stat-card">
<div class="stat-label">Current Price</div>
<div class="stat-value">$${format(stats.currentPrice)}</div>
</div>
<div class="stat-card">
<div class="stat-label">Min / Max</div>
<div class="stat-value">$${format(stats.minPrice)} / $${format(stats.maxPrice)}</div>
</div>
<div class="stat-card">
<div class="stat-label">Change</div>
<div class="stat-value ${stats.priceChange >= 0 ? 'positive' : 'negative'}">${format(stats.changePercent)}%</div>
</div>
<div class="stat-card">
<div class="stat-label">RSI (14)</div>
<div class="stat-value">${format(stats.currentRSI)}</div>
</div>
<div class="stat-card">
<div class="stat-label">Status</div>
<div class="stat-value">${stats.rsiStatus}</div>
</div>
`;
}
// Event listeners
document.getElementById('daysSlider').addEventListener('input', debounce(updateCharts, 500));
document.getElementById('rsiSlider').addEventListener('input', debounce(updateCharts, 500));
// Initial load
updateCharts();
</script>
</body>
</html>
)");
});
std::cout << "\n📈 Quantitative Finance Dashboard\n";
std::cout << "Listening on http://localhost:8080\n";
std::cout << "Opening browser...\n\n";
#ifdef _WIN32
system("start http://localhost:8080");
#elif __APPLE__
system("open http://localhost:8080");
#else
system("xdg-open http://localhost:8080 &");
#endif
app.port(8080).multithreaded().run();
return 0;
}