-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutility.js
1695 lines (1428 loc) · 60.1 KB
/
utility.js
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const yahooFinance = require('yahoo-finance2').default;
const mysql = require('mysql');
const fs = require('fs');
const csvParser = require('csv-parser');
const { interest_rate, simStartDay, lstIXIC, initialSimCash, numDaysToSimulate } = require('./config');
const { spawn } = require('child_process');
const path = require('path');
// // MySQL Database Connection
const db = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'client_password',
database: 'stock_data'
});
db.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL Database.');
});
// class object to analyzer stock(s)
// writeReturnsToCSV is used by PCA linear regression for algorithmic trading
class StockAnalysis {
constructor(tickers, startDate, endDate) {
this.dates = [];
this.tickers = tickers;
this.startDate = startDate;
this.endDate = endDate;
this.dailyPrices = [];
this.dailyDiffs = [];
this.logReturns = [];
this.totalLogReturn = [];
this.dailyReturns = [];
}
async fetchData() {
try {
for (const ticker of this.tickers) {
const result = await yahooFinance.historical(ticker, {
period1: this.startDate,
period2: this.endDate,
interval: '1d',
});
result.forEach((entry) => {
const date = entry.date.toISOString().split('T')[0]; // Format date as YYYY-MM-DD
if (!this.dates.includes(date)) {
this.dates.push(date); // Collect unique dates
}
if (!this.dailyPrices[ticker]) {
this.dailyPrices[ticker] = {};
}
this.dailyPrices[ticker][date] = entry.close;
});
}
} catch (error) {
throw new Error(`Error fetching data: ${error.message}`);
}
}
getDailyDifference() {
for (const ticker of this.tickers) {
const prices = this.dates.map((date) => this.dailyPrices[ticker]?.[date] || null);
this.dailyDiffs[ticker] = {}; // Initialize an empty object for the ticker's differences
for (let i = 1; i < prices.length; i++) {
if (prices[i] !== null && prices[i - 1] !== null) {
const date = this.dates[i];
this.dailyDiffs[ticker][date] = prices[i] - prices[i - 1];
}
}
}
}
getReturns() {
for (const ticker of this.tickers) {
const prices = this.dates.map((date) => this.dailyPrices[ticker]?.[date] || null);
this.dailyReturns[ticker] = {};
this.logReturns[ticker] = {};
for (let i = 1; i < prices.length; i++) {
if (prices[i] !== null && prices[i - 1] !== null && prices[i-1] !== 0) {
const dailyReturn = (prices[i] - prices[i - 1]) / prices[i - 1];
const logReturn = Math.log(prices[i] / prices[i - 1]);
const date = this.dates[i];
this.dailyReturns[ticker][date] = dailyReturn;
this.logReturns[ticker][date] = logReturn;
this.totalLogReturn[ticker] = Object.values(this.logReturns[ticker]).reduce((sum, val) => sum + val, 0);
// Debug log
// console.log(`Ticker: ${ticker}, Date: ${date}, Daily Return: ${dailyReturn}, Log Return: ${logReturn}`);
} else {
const dailyReturn = 0;
const logReturn = 0;
}
}
}
}
// Get cumulative log return (last log return - first log return)
getTotalReturn() {
const totalReturns = {};
for (const ticker of this.tickers) {
const prices = this.dates.map((date) => this.dailyPrices[ticker]?.[date]);
if (prices[0] !== null && prices[prices.length - 1] !== null) {
const startPrice = prices[0];
const endPrice = prices[prices.length - 1];
totalReturns[ticker] = (endPrice / startPrice) - 1;
} else {
totalReturns[ticker] = NaN; // Handle missing data
}
}
return totalReturns;
}
getMean() {
const allPrices = [];
for (const ticker of this.tickers) {
for (const date of this.dates) {
const price = this.dailyPrices[ticker]?.[date];
if (price !== undefined) allPrices.push(price);
}
}
return allPrices.length > 0
? allPrices.reduce((a, b) => a + b, 0) / allPrices.length
: NaN;
}
getStdDev() {
const allPrices = [];
for (const ticker of this.tickers) {
for (const date of this.dates) {
const price = this.dailyPrices[ticker]?.[date];
if (price !== undefined) allPrices.push(price);
}
}
if (allPrices.length <= 1) return NaN;
const mean = this.getMean();
const variance =
allPrices.reduce((sum, price) => sum + (price - mean) ** 2, 0) /
(allPrices.length - 1);
return Math.sqrt(variance);
}
getMin() {
const allPrices = [];
for (const ticker of this.tickers) {
for (const date of this.dates) {
const price = this.dailyPrices[ticker]?.[date];
if (price !== undefined) allPrices.push(price);
}
}
return allPrices.length > 0 ? Math.min(...allPrices) : NaN;
}
getMax() {
const allPrices = [];
for (const ticker of this.tickers) {
for (const date of this.dates) {
const price = this.dailyPrices[ticker]?.[date];
if (price !== undefined) allPrices.push(price);
}
}
return allPrices.length > 0 ? Math.max(...allPrices) : NaN;
}
getSharpeRatio() {
const sharpeRatios = {};
const rf_rate = interest_rate / 365;
// Ensure returns are properly calculated and available
this.getReturns();
for (const ticker of this.tickers) {
const returns = Object.values(this.dailyReturns[ticker] || []); // Convert to array for length and calculations
if (returns.length === 0) {
console.log(`No returns data for ${ticker}`);
sharpeRatios[ticker] = NaN;
continue;
}
// Calculate mean return
const meanReturn = returns.reduce((sum, r) => sum + r, 0) / returns.length;
// Calculate variance and standard deviation
const variance = returns.reduce((sum, r) => sum + (r - meanReturn) ** 2, 0) / (returns.length - 1);
const stdDev = Math.sqrt(variance);
if (stdDev === 0) {
sharpeRatios[ticker] = NaN; // Avoid division by zero
} else {
// Calculate Sharpe ratio
sharpeRatios[ticker] = (meanReturn - rf_rate) * Math.sqrt(252) / stdDev;
}
}
return sharpeRatios;
}
writeReturnsToCSV(outputFileName) {
const header = ['Date', ...this.tickers];
const rows = [header];
for (const date of this.dates) {
const row = [date];
this.tickers.forEach((ticker) => {
row.push(this.logReturns[ticker]?.[date]?.toFixed(6) || ''); // Fill missing with empty
});
rows.push(row);
}
const csvContent = rows.map((row) => row.join(',')).join('\n');
fs.writeFileSync(outputFileName, csvContent, 'utf8');
console.log(`Data written to ${outputFileName}`);
}
async analyze() {
await this.fetchData();
this.getDailyDifference();
this.getReturns();
this.getSharpeRatio();
return {
mean: this.getMean(),
standardDeviation: this.getStdDev(),
min: this.getMin(),
max: this.getMax(),
sharpeRatio: this.getSharpeRatio(),
dailyPrices: this.dailyPrices,
totalReturn: this.getTotalReturn(),
dailyDiffs: this.dailyDiffs,
dailyReturns: this.dailyReturns,
dailyLogReturns: this.logReturns,
};
}
}
// class object to analyzer portfolio
// read data from csv
class PortfolioAnalysis {
constructor(csvPath, columnName) {
this.csvPath = csvPath;
this.columnName = columnName; // The name of the column to analyze
this.date = [];
this.name = columnName;
this.dailyVal = [];
this.dailyChange = [];
this.percChange = [];
this.ytdChange = null;
this.ytdPercChange = null;
this.modDate = null;
this.loadData();
}
// Load data from the CSV file and process it
loadData() {
const filePath = path.resolve(this.csvPath);
// Read and parse the CSV file
const csvData = fs.readFileSync(filePath, 'utf-8');
const lines = csvData.split('\n').filter(line => line.trim() !== '');
// Extract headers and rows
const headers = lines[0].split(',').map(header => header.trim());
const rows = lines.slice(1).map(line => line.split(',').map(cell => cell.trim()));
// Find the index of the column by name
const columnIndex = headers.indexOf(this.columnName);
if (columnIndex === -1) {
throw new Error(`Column "${this.columnName}" not found in the CSV file.`);
}
// Process the data
rows.forEach(row => {
const date = row[0]; // First column is the date
const value = parseFloat(row[columnIndex]);
if (!isNaN(value)) {
this.date.push(date);
this.dailyVal.push(value);
}
});
// Calculate changes and percentage changes
this.calculateChanges();
}
// Calculate daily change, percentage change, YTD change, and YTD percentage change
calculateChanges() {
for (let i = 0; i < this.dailyVal.length; i++) {
if (i === 0) {
this.dailyChange.push(0); // No change for the first day
this.percChange.push(0); // No percentage change for the first day
} else {
const change = this.dailyVal[i] - this.dailyVal[i - 1];
const percChange = (change / this.dailyVal[i - 1]) * 100;
this.dailyChange.push(change);
this.percChange.push(percChange);
}
}
// Calculate YTD change and YTD percentage change
const firstVal = this.dailyVal[0];
const lastVal = this.dailyVal[this.dailyVal.length - 1];
this.ytdChange = lastVal - firstVal;
this.ytdPercChange = ((lastVal - firstVal) / firstVal) * 100;
this.modDate = this.date[this.date.length - 1];
}
// Display the calculated data
displayAnalysis(bDisplayDaily = false) {
console.log(`Portfolio Analysis for ${this.name} on date ${this.modDate}:`);
console.log(`YTD Change: ${this.ytdChange.toFixed(2)}`);
console.log(`YTD Percentage Change: ${this.ytdPercChange.toFixed(2)}%`);
if (bDisplayDaily){
console.log('Daily Data:');
for (let i = 0; i < this.date.length; i++) {
console.log(
`${this.date[i]} - Value: ${this.dailyVal[i].toFixed(2)}, ` +
`Change: ${this.dailyChange[i].toFixed(2)}, ` +
`% Change: ${this.percChange[i].toFixed(2)}%`
);
}};
}
}
// const portfolio = new PortfolioAnalysis('./output/portfolio_history.csv', 'Cash+Strategic');
// portfolio.displayAnalysis();
// get stock prices from CSV
// getStockFromCSV('AAPL','2024-10-02', './input/stock_prices.csv')
async function getStockFromCSV(symbols, date, csvPath) {
return new Promise((resolve, reject) => {
const stockPrices = {};
// Open the CSV file and parse it
fs.createReadStream(csvPath)
.pipe(csvParser())
.on('data', (row) => {
// Assume the first column is the date and the first row contains symbols
const rowDate = row['Date']; // Assuming the first column is 'Date'
if (rowDate === date) {
// For each symbol, check if it matches the given symbols
for (let i = 1; i < Object.keys(row).length - 1; i++) {
const symbol = Object.keys(row)[i];
if (symbols.includes(symbol)) {
// Store the stock price for the symbol and date
stockPrices[symbol] = parseFloat(row[symbol]);
}
}
}
})
.on('end', () => {
// Once all rows are processed, resolve the promise with the stock prices
resolve(stockPrices);
})
.on('error', (err) => {
// Reject the promise in case of an error
reject(err);
});
});
}
// Fetch Stock Data from Yahoo Finance
async function getStockData(symbol, today) {
try {
const data = await yahooFinance.historical(symbol, {
period1: '2019-01-01',
period2: today,
interval: '1d',
});
console.log('updated stock price(s).')
return data;
} catch (error) {
console.error('Error fetching stock data:', error);
throw new Error('Failed to fetch stock data');
}
}
// Trade stock type = 'manual/ strategic/ algorithmic'
// quantity > 0 --> buy; quantity < 0 --> sell
async function tradeStock(userID, ticker, quantity, date, type) {
if (quantity === 0) {
throw new Error("Quantity must not be zero.");
}
const connection = db;
try {
// Begin transaction
await new Promise((resolve, reject) =>
connection.beginTransaction((err) => (err ? reject(err) : resolve()))
);
const isBuying = quantity > 0;
// Fetch the stock price for the given ticker and date
console.log(`Fetching stock price for ${ticker} on ${date}...`);
const priceRows = await new Promise((resolve, reject) =>
connection.query(
'SELECT Price FROM stock_prices WHERE Ticker = ? AND Date = ?',
[ticker, date],
(err, results) => (err ? reject(err) : resolve(results))
)
);
console.log('Price rows retrieved:', priceRows);
if (priceRows.length === 0) {
console.log(`No stock price found for ${ticker} on ${date}. Updating stock prices.`);
await getStockData(ticker, date);
const updatedPriceRows = await new Promise((resolve, reject) =>
connection.query(
'SELECT Price FROM stock_prices WHERE Ticker = ? AND Date = ?',
[ticker, date],
(err, results) => (err ? reject(err) : resolve(results))
)
);
console.log('Updated price rows:', updatedPriceRows);
if (updatedPriceRows.length === 0) {
throw new Error(`Unable to retrieve price for ${ticker} on ${date} after update.`);
}
priceRows.push(updatedPriceRows[0]);
}
const price = priceRows[0].Price;
const totalCostOrRevenue = price * Math.abs(quantity);
// console.log(`Price for ${ticker} on ${date}: ${price}`);
// console.log(`Total cost/revenue for ${ticker}: ${totalCostOrRevenue}`);
// Check if the user has a portfolio of the specified type
// console.log(`Fetching portfolio for user ${userID} and type ${type}...`);
const portfolioRows = await new Promise((resolve, reject) =>
connection.query(
'SELECT PortfolioID, TotalValue FROM Portfolios WHERE UserID = ? AND PortfolioType = ?',
[userID, type],
(err, results) => (err ? reject(err) : resolve(results))
)
);
console.log('Portfolio rows retrieved:', portfolioRows);
let portfolioID;
let portfolioValue;
if (portfolioRows.length === 0) {
// Initialize the portfolio if it doesn't exist
console.log(`Initializing new portfolio for type ${type}...`);
const result = await new Promise((resolve, reject) =>
connection.query(
'INSERT INTO Portfolios (UserID, TotalValue, PortfolioType, modDate) VALUES (?, ?, ?, ?)',
[userID, 0, type, date],
(err, results) => (err ? reject(err) : resolve(results))
)
);
console.log('Portfolio INSERT result:', result);
if (result && result.insertId) {
portfolioID = result.insertId;
portfolioValue = 0;
} else {
throw new Error("Failed to initialize new portfolio. insertId is missing.");
}
} else {
portfolioID = portfolioRows[0].PortfolioID;
portfolioValue = portfolioRows[0].TotalValue;
}
// Fetch the user's holdings for the specified stock
console.log(`Fetching holdings for ticker ${ticker}...`);
const holdingRows = await new Promise((resolve, reject) =>
connection.query(
'SELECT HoldingID, Quantity FROM Portfolio_Holdings WHERE PortfolioID = ? AND Ticker = ?',
[portfolioID, ticker],
(err, results) => (err ? reject(err) : resolve(results))
)
);
console.log('Holding rows retrieved:', holdingRows);
let currentQuantity = holdingRows.length > 0 ? holdingRows[0].Quantity : 0;
if (!isBuying) {
// Validate sell constraints
if (type !== 'algorithmic' && currentQuantity < Math.abs(quantity)) {
throw new Error(`Cannot sell more shares than owned for portfolio type '${type}'.`);
}
currentQuantity -= Math.abs(quantity); // Deduct quantity for selling
} else {
currentQuantity += quantity; // Add quantity for buying
}
// Update or insert the holding
if (holdingRows.length > 0) {
if (currentQuantity === 0) {
console.log(`Deleting holding for ticker ${ticker}...`);
await new Promise((resolve, reject) =>
connection.query(
'DELETE FROM Portfolio_Holdings WHERE HoldingID = ?',
[holdingRows[0].HoldingID],
(err) => (err ? reject(err) : resolve())
)
);
} else {
console.log(`Updating holding for ticker ${ticker}...`);
await new Promise((resolve, reject) =>
connection.query(
'UPDATE Portfolio_Holdings SET Quantity = ? WHERE HoldingID = ?',
[currentQuantity, holdingRows[0].HoldingID],
(err) => (err ? reject(err) : resolve())
)
);
}
} else if (currentQuantity != 0) {
console.log(`Inserting holding for ticker ${ticker}...`);
await new Promise((resolve, reject) =>
connection.query(
'INSERT INTO Portfolio_Holdings (PortfolioID, Ticker, Quantity) VALUES (?, ?, ?)',
[portfolioID, ticker, currentQuantity],
(err) => (err ? reject(err) : resolve())
)
);
}
// Update the portfolio's total value
const updatedPortfolioValue = isBuying
? portfolioValue + totalCostOrRevenue
: portfolioValue - totalCostOrRevenue;
console.log(`Updating portfolio total value to ${updatedPortfolioValue}...`);
await new Promise((resolve, reject) =>
connection.query(
'UPDATE Portfolios SET TotalValue = ? WHERE PortfolioID = ?',
[updatedPortfolioValue, portfolioID],
(err) => (err ? reject(err) : resolve())
)
);
// Update the cash portfolio
console.log(`Fetching cash portfolio for user ${userID}...`);
const cashPortfolioRows = await new Promise((resolve, reject) =>
connection.query(
'SELECT PortfolioID, TotalValue FROM Portfolios WHERE UserID = ? AND PortfolioType = ?',
[userID, 'cash'],
(err, results) => (err ? reject(err) : resolve(results))
)
);
console.log('Cash portfolio rows retrieved:', cashPortfolioRows);
if (cashPortfolioRows.length === 0) {
throw new Error('User does not have a cash portfolio.');
}
const cashPortfolioID = cashPortfolioRows[0].PortfolioID;
const cashUpdateValue = isBuying ? -totalCostOrRevenue : totalCostOrRevenue;
console.log(`Updating cash portfolio value by ${cashUpdateValue}...`);
await new Promise((resolve, reject) =>
connection.query(
'UPDATE Portfolios SET TotalValue = TotalValue + ? WHERE PortfolioID = ?',
[cashUpdateValue, cashPortfolioID],
(err) => (err ? reject(err) : resolve())
)
);
// Record the transaction
const transactionType = isBuying ? 'BUY' : 'SELL';
console.log(`Recording transaction for ${ticker}...`);
await new Promise((resolve, reject) =>
connection.query(
'INSERT INTO Transactions (UserID, Ticker, TransactionType, Quantity, Price, Date) VALUES (?, ?, ?, ?, ?, ?)',
[userID, ticker, transactionType, quantity, price, date],
(err, results) => (err ? reject(err) : resolve(results))
)
);
// Commit the transaction
await new Promise((resolve, reject) =>
connection.commit((err) => (err ? reject(err) : resolve()))
);
console.log(`Stock ${ticker} ${transactionType} successfully completed.`);
} catch (error) {
await new Promise((resolve, reject) =>
connection.rollback((err) => (err ? reject(err) : resolve()))
);
console.error('Error trading stock:', error.message);
throw error;
}
}
// update MySQL table 'stock_prices' based on 'date'
async function updateStockPrices(date) {
const connection = db;
let stock_count = 0;
try {
// Begin transaction to ensure all updates are done atomically
await new Promise((resolve, reject) =>
connection.beginTransaction((err) => (err ? reject(err) : resolve()))
);
// Fetch all unique tickers from the stock prices table
const tickers = await new Promise((resolve, reject) =>
connection.query(
'SELECT DISTINCT Ticker FROM stock_prices',
(err, results) => (err ? reject(err) : resolve(results))
)
);
for (const tickerRow of tickers) {
const ticker = tickerRow.Ticker;
// console.log(`Fetching stock data for ${ticker} up to ${date}...`);
// Fetch the last available stock price date for this ticker
const lastPriceDateRow = await new Promise((resolve, reject) =>
connection.query(
'SELECT MAX(Date) AS LastDate FROM stock_prices WHERE Ticker = ?',
[ticker],
(err, results) => (err ? reject(err) : resolve(results))
)
);
const lastDate = lastPriceDateRow[0].LastDate;
let startDate = lastDate ? new Date(lastDate) : new Date('2019-01-01'); // Default to 2019 if no previous data
// Ensure the start date is the next day after the last recorded date
startDate.setDate(startDate.getDate() + 1);
const formattedStartDate = startDate.toISOString().split('T')[0];
// Only fetch data from the last date to the requested date
if (startDate <= new Date(date)) {
const stockData = await yahooFinance.historical(ticker, {
period1: formattedStartDate, // Start from the next day after last available date
period2: date, // Up to the specified date
interval: '1d', // Daily interval
});
// Insert or update stock data in the database
for (const data of stockData) {
const { date: stockDate, close: stockPrice } = data;
// Format the date to match the format in the database (e.g., 'YYYY-MM-DD')
const formattedDate = stockDate.toISOString().split('T')[0];
// Check if the price for this date already exists
const existingPriceRows = await new Promise((resolve, reject) =>
connection.query(
'SELECT * FROM stock_prices WHERE Ticker = ? AND Date = ?',
[ticker, formattedDate],
(err, results) => (err ? reject(err) : resolve(results))
)
);
if (existingPriceRows.length === 0) {
// If no price exists, insert the new data
await new Promise((resolve, reject) =>
connection.query(
'INSERT INTO stock_prices (Ticker, Date, Price) VALUES (?, ?, ?)',
[ticker, formattedDate, stockPrice],
(err) => (err ? reject(err) : resolve())
)
);
stock_count += 1;
// console.log(`Inserted price for ${ticker} on ${formattedDate}: ${stockPrice}`);
} else {
// If price exists, update the existing record
await new Promise((resolve, reject) =>
connection.query(
'UPDATE stock_prices SET Price = ? WHERE Ticker = ? AND Date = ?',
[stockPrice, ticker, formattedDate],
(err) => (err ? reject(err) : resolve())
)
);
// console.log(`Updated price for ${ticker} on ${formattedDate}: ${stockPrice}`);
}
}
} else {
// console.log(`No data needed for ${ticker} since the last update is already up-to-date.`);
}
}
// Commit the transaction
await new Promise((resolve, reject) =>
connection.commit((err) => (err ? reject(err) : resolve()))
);
console.log(stock_count, 'stock prices and index updated successfully up to', date);
} catch (error) {
// Rollback in case of an error
await new Promise((resolve, reject) =>
connection.rollback((err) => (err ? reject(err) : resolve()))
);
console.error('Error updating stock prices:', error.message);
throw error;
}
}
// calculate number of days from start
function calculateDaysFromStart(cDate, sDate) {
const startDate = new Date(sDate); // Parse the start date string
const currentDate = new Date(cDate); // Get the current date
// Calculate the difference in time between the two dates
const timeDifference = currentDate - startDate;
// Convert the time difference from milliseconds to days
const daysDifference = timeDifference / (1000 * 3600 * 24);
return Math.floor(daysDifference); // Return the difference as a whole number
}
async function increaseDateBy(currDate, days) {
const date = new Date(currDate); // Create a Date object from the current date string
date.setDate(date.getDate() + days + 1); // Increase the date by the specified number of days
// Format the resulting date as 'YYYY-MM-DD'
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed, so add 1
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`; // Return the formatted date
}
async function updatePortfolioValue(userID, date) {
const connection = db;
try {
// Begin transaction to ensure all updates are done atomically
await new Promise((resolve, reject) =>
connection.beginTransaction((err) => (err ? reject(err) : resolve()))
);
// Fetch all portfolios for the user
const portfolios = await new Promise((resolve, reject) =>
connection.query(
'SELECT PortfolioID, UserID, TotalValue, PortfolioType, modDate FROM Portfolios WHERE UserID = ?',
[userID],
(err, results) => (err ? reject(err) : resolve(results))
)
);
// Process each portfolio
for (const portfolio of portfolios) {
const { PortfolioID, PortfolioType, TotalValue } = portfolio;
let newTotalValue = TotalValue;
if (PortfolioType === 'cash') {
console.log('looking at cash portfolio');
// For 'cash' portfolio, apply continuous compounding interest (2% annual rate)
// console.log(`new date is ${date}`);
const mod_date = new Date(portfolio.modDate);
const formattedDate = mod_date.toISOString().split('T')[0];
// console.log(`mod date is ${formattedDate}`);
const timeInYears = calculateDaysFromStart(date, formattedDate) / 365;
const interestRate = interest_rate;
// console.log(interestRate);
newTotalValue = TotalValue * Math.exp(interestRate * timeInYears);
if (isNaN(newTotalValue)){
console.log(`NaN on ${date}. Using old value`);
newTotalValue = TotalValue;
}
// console.log(`old ${TotalValue}, new ${newTotalValue}, time ${timeInYears}`);
// Update the cash portfolio value in the Portfolios table
await new Promise((resolve, reject) =>
connection.query(
'UPDATE Portfolios SET TotalValue = ?, modDate = ? WHERE PortfolioID = ? AND UserID = ?',
[newTotalValue, date, PortfolioID, userID],
(err) => (err ? reject(err) : resolve())
)
);
console.log(`Updated cash portfolio ${PortfolioID} value to ${newTotalValue}`);
// Write cash portfolio to Portfolio_Value_History
await new Promise((resolve, reject) =>
connection.query(
'INSERT INTO Portfolio_Value_History (UserID, PortfolioID, Date, TotalValue) VALUES (?, ?, ?, ?)',
[userID, PortfolioID, date, newTotalValue],
(err) => (err ? reject(err) : resolve())
)
);
console.log(`Inserted cash portfolio ${PortfolioID} value history for ${date}`);
} else {
// For other types of portfolios, calculate the total value based on shares and stock prices
newTotalValue = 0;
// Fetch the stock holdings for this portfolio
const holdings = await new Promise((resolve, reject) =>
connection.query(
'SELECT Ticker, Quantity FROM Portfolio_Holdings WHERE PortfolioID = ?',
[PortfolioID],
(err, results) => (err ? reject(err) : resolve(results))
)
);
// For each stock holding, get its price on the specified date and calculate the total value
for (const holding of holdings) {
const { Ticker, Quantity } = holding;
// Fetch the stock price for the specified date
let stockPriceRows = await new Promise((resolve, reject) =>
connection.query(
'SELECT Price FROM stock_prices WHERE Ticker = ? AND Date = ?',
[Ticker, date],
(err, results) => (err ? reject(err) : resolve(results))
)
);
if (stockPriceRows.length === 0) {
console.log(`No price found for ${Ticker} on ${date}. Searching for the last available price.`);
// If no price is found for the given date, fetch the most recent price
stockPriceRows = await new Promise((resolve, reject) =>
connection.query(
'SELECT Price FROM stock_prices WHERE Ticker = ? AND Date <= ? ORDER BY Date DESC LIMIT 1',
[Ticker, date],
(err, results) => (err ? reject(err) : resolve(results))
)
);
if (stockPriceRows.length === 0) {
console.log(`No price available for ${Ticker}. Skipping.`);
continue; // Skip this stock if no historical price is found
}
console.log(`Using last available price for ${Ticker}: ${stockPriceRows[0].Price}`);
}
const stockPrice = stockPriceRows[0].Price;
const stockValue = stockPrice * Quantity;
newTotalValue += stockValue;
}
// Update the portfolio's total value in the Portfolios table
await new Promise((resolve, reject) =>
connection.query(
'UPDATE Portfolios SET TotalValue = ?, modDate = ? WHERE PortfolioID = ? AND UserID = ?',
[newTotalValue, date, PortfolioID, userID],
(err) => (err ? reject(err) : resolve())
)
);
// console.log(`Updated portfolio ${PortfolioID} value to ${newTotalValue}`);
// Write non-cash portfolio to Portfolio_Value_History
await new Promise((resolve, reject) =>
connection.query(
'INSERT INTO Portfolio_Value_History (UserID, PortfolioID, Date, TotalValue) VALUES (?, ?, ?, ?)',
[userID, PortfolioID, date, newTotalValue],
(err) => (err ? reject(err) : resolve())
)
);
console.log(`Inserted portfolio ${PortfolioID} value history for ${date}`);
}
}
// Commit the transaction
await new Promise((resolve, reject) =>
connection.commit((err) => (err ? reject(err) : resolve()))
);
console.log('All portfolios updated successfully.');
} catch (error) {
// Rollback the transaction in case of an error
await new Promise((resolve, reject) =>
connection.rollback((err) => (err ? reject(err) : resolve()))
);
console.error('Error updating portfolio values:', error.message);
throw error;
}
}
// async python child process for machine learning functions
async function callPythonProcess(csvFilePath) {
return new Promise((resolve, reject) => {
// Path to the Python script
const pythonScript = path.resolve('./pca_linreg.py');
// Spawn the Python process
const pythonProcess = spawn('python', [pythonScript, csvFilePath]);
let output = '';
let errorOutput = '';
// Capture Python script's stdout
pythonProcess.stdout.on('data', (data) => {
output += data.toString();
});
// Capture Python script's stderr
pythonProcess.stderr.on('data', (data) => {
errorOutput += data.toString();
});
// Handle process exit
pythonProcess.on('close', (code) => {
if (code === 0) {
try {
// Parse JSON output from Python script
const result = JSON.parse(output);
resolve(result);
} catch (err) {
reject(`Error parsing JSON: ${err.message}`);
}
} else {
reject(`Python process exited with code ${code}: ${errorOutput}`);
}
});
// Handle process errors
pythonProcess.on('error', (error) => {
reject(`Failed to start Python process: ${error.message}`);
});
});
}
function getAnalysisStartDate(currentDate, timeHorizon) {
// Parse the currentDate string into a JavaScript Date object
const current = new Date(currentDate);
// Subtract the timeHorizon in years from the current date
current.setFullYear(current.getFullYear() - timeHorizon);
// Format the result as 'YYYY-MM-DD'
const year = current.getFullYear();
const month = String(current.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed
const day = String(current.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
async function portfolio_by_PCA(userID, totalValue, symbols, weights, prices, date) {
// Validate input lengths
if (symbols.length !== weights.length || symbols.length !== prices.length) {
throw new Error('Symbols, weights, and prices arrays must be of the same length.');
}
console.log('Starting portfolio update using PCA recommendations...');
console.log(`with ${totalValue} cash`);
for (let i = 0; i < symbols.length; i++) {
const ticker = symbols[i];
const weight = weights[i];
const price = prices[i];
// Calculate number of shares to buy
const quantity = Math.ceil((totalValue * weight) / price);
if (quantity === 0) {
console.log(`Skipping ${ticker}: calculated quantity is 0.`);
continue;
}
try {
console.log(`Processing trade for ${ticker}: Buying ${quantity} shares at price ${price}.`);
await tradeStock(userID, ticker, quantity, date, 'algorithmic');
console.log(`Successfully traded ${ticker}.`);
} catch (error) {
console.error(`Error trading ${ticker}: ${error.message}`);
}
}
console.log('Portfolio update completed.');
}
// async function to call python process with defined parameters
async function PCA_analysis(userID, analysis_start_date, analysis_end_date, totalValue, trade_date) {
const analysis = new StockAnalysis(lstIXIC, analysis_start_date, analysis_end_date, interest_rate);
try {
console.log(`begin machine learning process.`);
// Fetch and process data
await analysis.fetchData();
console.log(`calculating log returns of stocks during analysis period`);
analysis.getReturns();
analysis.writeReturnsToCSV('./input/log_returns.csv');
// Call the Python process with the CSV file
const csvFilePath = './input/log_returns.csv';
console.log(`calculating portfolio compositions.`)
const result = await callPythonProcess(csvFilePath);