-
Notifications
You must be signed in to change notification settings - Fork 0
/
Home.js
578 lines (518 loc) · 18.4 KB
/
Home.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
import React, { useContext, useState } from 'react';
import { View, Text, Button, FlatList, TouchableOpacity, Pressable, StyleSheet, TextInput, Alert, KeyboardAvoidingView, Platform } from 'react-native';
import DateTimePicker from '@react-native-community/datetimepicker';
import axios from 'axios';
import * as PortfolioAllocation from 'portfolio-allocation';
import Icon from 'react-native-vector-icons/Ionicons';
import { useNavigation } from '@react-navigation/native';
import { AppContext } from './AppContext'; // Import the AppContext
const stocks = [
'aapl', // Apple Inc.
'amd', // Advanced Micro Devices Inc.
'amzn', // Amazon.com Inc.
'f', // Ford Motor Co.
'goog', // Alphabet Inc. (Google)
'gs', // Goldman Sachs Group Inc.
'intc', // Intel Corp.
'ko', // Coca-Cola Co.
'meta', // Meta Platforms Inc. (Facebook)
'msft', // Microsoft Corp.
'nflx', // Netflix Inc.
'nvda', // NVIDIA Corp.
'tsla', // Tesla Inc.
'v', // Visa Inc.
'axp', // American Express Co.
'ba', // Boeing Co.
'cat', // Caterpillar Inc.
'csco', // Cisco Systems Inc.
'cvx', // Chevron Corp.
'dis', // Walt Disney Co.
'dow', // Dow Inc.
'hd', // Home Depot Inc.
'hon', // Honeywell International Inc.
'ibm', // International Business Machines Corp.
'jnj', // Johnson & Johnson
'jpm', // JPMorgan Chase & Co.
'mcd', // McDonald's Corp.
'mmm', // 3M Co.
'mrk', // Merck & Co. Inc.
'nke', // Nike Inc.
'pg', // Procter & Gamble Co.
'trv', // Travelers Companies Inc.
'unh', // UnitedHealth Group Inc.
];
const Home = () => {
const navigation = useNavigation();
const { isDarkMode } = useContext(AppContext); // Access context here
const [selectedStocks, setSelectedStocks] = useState([]);
const tenDaysAgo = new Date();
tenDaysAgo.setDate(tenDaysAgo.getDate() - 30);
const [startDate, setStartDate] = useState(tenDaysAgo);
const [endDate, setEndDate] = useState(new Date());
const [results, setResults] = useState(null);
const [riskFreeRate, setRiskFreeRate] = useState(0.0);
const [totalAmount, setTotalAmount] = useState(1000);
const [searchTerm, setSearchTerm] = useState('');
const [basket, setBasket] = useState([]);
// Section for Model
const fetchDataAndRunModel = async () => {
setResults(null);
const sortedBasket = [...basket].sort();
console.log('\n\nSelected Stocks: ', sortedBasket);
try {
const stockData = await fetchStockData(sortedBasket, startDate, endDate);
console.log('\n\nStockData:', stockData);
const modelResults = runModel(stockData, sortedBasket);
setResults(modelResults);
} catch (error) {
Alert.alert('Error', 'The input list cannot be empty. Please check the basket or date length.');
}
};
const fetchStockData = async (tickers, startDate, endDate) => {
const formatDate = (date) => {
return date.toISOString().split('T')[0];
};
const fetchTickerData = async (ticker) => {
const url = `https://query1.finance.yahoo.com/v7/finance/download/${ticker}?period1=${Math.floor(new Date(startDate).getTime() / 1000)}&period2=${Math.floor(new Date(endDate).getTime() / 1000)}&interval=1d&events=history`;
const response = await axios.get(url);
console.log('\n Catched data from Server\n:', response, '\n\n');
const rows = response.data.split('\n').slice(1);
const formattedRows = rows.map(row => {
const [date, , , , , adj_close,] = row.split(',');
return { date, tic: ticker, adj_close: parseFloat(adj_close) };
});
console.log('\nFetched Data for', ticker, ':', formattedRows, '\n\n'); // Log the fetched data
return formattedRows;
};
const promises = tickers.map(ticker => fetchTickerData(ticker));
const results = await Promise.all(promises);
return results.flat();
};
const runModel = (data, sortedBasket) => {
const processDfForMvo = (df) => {
const stockDimension = df.length / sortedBasket.length;
df.sort((a, b) => (a.date > b.date ? 1 : -1));
let tic = [...new Set(df.map((item) => item.tic))];
let mvo = {};
tic.forEach((t) => {
mvo[t] = [];
});
for (let i = 0; i < df.length; i++) {
mvo[df[i].tic].push(df[i].adj_close);
}
let dates = [...new Set(df.map((item) => item.date))];
let result = dates.map((date) => {
let row = { date: date };
tic.forEach((t) => {
let index = df.findIndex((item) => item.date === date && item.tic === t);
row[t] = index !== -1 ? df[index].adj_close : 0;
});
return row;
});
return result;
};
const stockReturnsComputing = (stockPrices) => {
const rows = stockPrices.length;
const cols = stockPrices[0].length; // Number of assets
let stockReturn = Array(rows - 1)
.fill()
.map(() => Array(cols).fill(0));
for (let j = 0; j < cols; j++) { // j: Assets
for (let i = 0; i < rows - 1; i++) { // i: Daily Prices
let prevPrice = stockPrices[i][j];
let currPrice = stockPrices[i + 1][j];
stockReturn[i][j] = ((currPrice - prevPrice) / prevPrice) * 100;
}
}
return stockReturn;
};
const calculateMeanReturns = (arReturns) => {
const rows = arReturns.length;
const cols = arReturns[0].length;
let meanReturns = Array(cols).fill(0);
for (let j = 0; j < cols; j++) { // Loop through columns (assets)
for (let i = 0; i < rows; i++) { // Loop through rows (daily returns)
meanReturns[j] += arReturns[i][j];
}
meanReturns[j] /= rows; // Divide by the number of rows to get the mean
}
return meanReturns;
};
const calculateCovarianceMatrix = (returns, meanReturns) => {
const rows = returns.length;
const cols = returns[0].length;
let covarianceMatrix = Array(cols)
.fill()
.map(() => Array(cols).fill(0));
for (let i = 0; i < cols; i++) {
for (let j = 0; j < cols; j++) {
let cov = 0;
for (let k = 0; k < rows; k++) {
cov += (returns[k][i] - meanReturns[i]) * (returns[k][j] - meanReturns[j]);
}
covarianceMatrix[i][j] = cov / (rows - 1);
}
}
return covarianceMatrix;
};
const calculateMaxSharpe = (meanReturns, covReturns) => {
const nbPortfolios = 100; // Number of portfolios to generate on the efficient frontier
const portfolios = PortfolioAllocation.meanVarianceEfficientFrontierPortfolios(meanReturns, covReturns, {
nbPortfolios: nbPortfolios,
discretizatinType: 'return', // Generate portfolios based on return
});
// Find the portfolio with the maximum Sharpe Ratio
const riskFreeRate = 0; // Risk-free rate, adjust as needed
let maxSharpeRatio = -Infinity;
let maxSharpeWeights = [];
portfolios.forEach(([weights, portfolioReturn, portfolioVolatility]) => {
const sharpeRatio = (portfolioReturn - riskFreeRate) / portfolioVolatility;
if (sharpeRatio > maxSharpeRatio) {
maxSharpeRatio = sharpeRatio;
maxSharpeWeights = weights;
}
});
const scaledWeights = maxSharpeWeights.map(weight => weight * totalAmount);
return scaledWeights;
};
const calculateERC = (covReturns) => {
const ercWeights = PortfolioAllocation.equalRiskContributionWeights(covReturns);
const scaledWeights = ercWeights.map(weight => weight * totalAmount);
return scaledWeights;
};
const stockData = processDfForMvo(data);
console.log('First Step Process', stockData, '\n\n\n\n\n\n\n');
const arStockPrices = stockData.map((row) => {
const { date, ...prices } = row;
return Object.keys(prices).sort().map(key => prices[key]);
});
console.log('\n\n arStockPrices:', arStockPrices);
const [rows, cols] = [arStockPrices.length, arStockPrices[0].length];
const arReturns = stockReturnsComputing(arStockPrices); //arReturns is Asset return in 100% scale
console.log('\n\n arReturns:', arReturns);
const meanReturns = calculateMeanReturns(arReturns); // still in 100%
console.log('\n\n meanReturns:', meanReturns);
const covReturns = calculateCovarianceMatrix(arReturns, meanReturns); // Calculate the Covariance value
console.log('Con Variance Value: ', covReturns);
// Compute the maximum Sharpe ratio portfolio weights
const maxSharpeWeights = calculateMaxSharpe(meanReturns, covReturns);
console.log('Max Sharpe Weights: ', maxSharpeWeights);
const ercWeights = calculateERC(covReturns); // Implement ERC calculation
console.log('ERC Weights: ', ercWeights);
return { meanReturns, covReturns, maxSharpeWeights, ercWeights };
};
// Below just display and the visualization
const toggleStockSelection = (stock) => {
setSelectedStocks((prevSelected) =>
prevSelected.includes(stock)
? prevSelected.filter((item) => item !== stock)
: [...prevSelected, stock]
);
};
const addToBasket = () => {
const newStocks = selectedStocks.filter(stock => !basket.includes(stock));
setBasket([...basket, ...newStocks]);
setSelectedStocks([]);
};
const clearBasket = () => {
setBasket([]);
setResults(null);
};
const onChangeStart = (event, selectedDate) => {
const currentDate = selectedDate || startDate;
setStartDate(currentDate);
};
const onChangeEnd = (event, selectedDate) => { // 这个event 不能删, 不知道为啥,但是有用
const currentDate = selectedDate || endDate;
setEndDate(currentDate);
};
const capitalize = (str) => (str ? str.toUpperCase() : '');
const filteredStocks = stocks.filter(stock => stock.toUpperCase().includes(searchTerm.toUpperCase()));
const styles = StyleSheet.create({
container: {
marginTop: 40,
padding: 20,
paddingBottom: 50,
backgroundColor: isDarkMode ? '#333' : '#f0f0f0', // Use isDarkMode here
flex: 1,
},
header: {
fontSize: 18,
fontWeight: 'bold',
marginBottom: 10,
},
headerContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
searchInput: {
borderWidth: 1,
borderColor: '#ccc',
padding: 10,
borderRadius: 5,
marginBottom: 10,
backgroundColor: 'white',
},
stockRow: {
flexDirection: 'row',
justifyContent: 'space-between',
marginVertical: 5,
},
stockItem: {
flex: 1,
height: 30,
marginHorizontal: 5,
backgroundColor: '#8E8E93', // iOS system gray color
borderRadius: 5,
justifyContent: 'center',
alignItems: 'center',
},
selectedStockItem: {
backgroundColor: '#34C759', // iOS system green color
},
stockText: {
color: 'white',
fontSize: 14,
textAlign: 'center',
lineHeight: 30, // lineHeight 和 stockItem 的hight 要一致
},
inputContainer: {
marginVertical: 10,
},
inputLabel: {
fontSize: 16,
marginBottom: 5,
},
input: {
borderWidth: 1,
borderColor: '#ccc',
padding: 10,
borderRadius: 5,
backgroundColor: 'white',
},
datePickerContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
marginVertical: 10,
},
datePicker: {
flex: 1,
marginRight: 10,
alignContent: 'center'
},
datePickerText: {
fontSize: 16,
marginBottom: 5,
textAlign: 'center',
},
datePickerWrapper: {
flex: 1,
alignItems: 'center',
marginRight: 20,
},
runButton: {
marginVertical: 20,
},
resultsContainer: {
marginVertical: 20,
},
resultCard: {
backgroundColor: 'white',
padding: 15,
marginBottom: 10,
borderRadius: 10,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.2,
shadowRadius: 5,
},
resultHeader: {
fontSize: 16,
fontWeight: 'bold',
},
resultContent: {
fontSize: 14,
marginTop: 5,
},
resultHeaderContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
basketContainer: {
marginBottom: 20,
},
basketHeader: {
fontSize: 16,
fontWeight: 'bold',
},
basketItems: {
flexDirection: 'row',
flexWrap: 'wrap',
marginTop: 10,
},
basketItem: {
fontSize: 14,
marginRight: 10,
backgroundColor: '#e0e0e0',
padding: 5,
borderRadius: 5,
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
marginVertical: 5,
padding: 10,
borderRadius: 5,
},
button: {
flex: 1,
padding: 10,
backgroundColor: '#007BFF',
borderRadius: 5,
alignItems: 'center',
marginHorizontal: 5,
},
buttonText: {
color: 'white',
fontSize: 16,
},
});
return (
<FlatList
style={styles.container}
data={filteredStocks}
keyExtractor={(item) => item}
ListHeaderComponent={() => (
<>
<View style={styles.headerContainer}>
<Text style={styles.header}>Search and Select Stocks:</Text>
<Pressable onPress={() => navigation.navigate('Settings')}>
<Icon name="ellipsis-horizontal" size={24} color="black" />
</Pressable>
</View>
<TextInput
style={styles.searchInput}
placeholder="Search stocks..."
value={searchTerm}
onChangeText={setSearchTerm}
/>
{filteredStocks.slice(0, 10).reduce((rows, stock, index) => {
if (index % 5 === 0) rows.push([]);
rows[rows.length - 1].push(stock);
return rows;
}, []).map((row, rowIndex) => (
<View key={rowIndex} style={styles.stockRow}>
{row.map((stock) => (
<TouchableOpacity key={stock} onPress={() => toggleStockSelection(stock)} style={[styles.stockItem,
selectedStocks.includes(stock) && styles.selectedStockItem,]}>
<Text style={styles.stockText}> {capitalize(stock)} </Text>
</TouchableOpacity>
))}
</View>
))}
<View style={styles.buttonContainer}>
<TouchableOpacity style={styles.button} onPress={addToBasket}>
<Text style={styles.buttonText}>Add to Basket</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button} onPress={clearBasket}>
<Text style={styles.buttonText}>Clear Basket</Text>
</TouchableOpacity>
</View>
<View style={styles.basketContainer}>
<Text style={styles.basketHeader}>Basket:</Text>
<View style={styles.basketItems}>
{basket.sort().map((stock, index) => (
<Text key={index} style={styles.basketItem}>{capitalize(stock)}</Text>
))}
</View>
</View>
<View style={styles.inputContainer}>
<Text style={styles.inputLabel}>Risk-Free Rate:</Text>
<TextInput
style={styles.input}
value={riskFreeRate ? String(riskFreeRate) : ''}
onChangeText={(text) => setRiskFreeRate(parseFloat(text) || 0)}
keyboardType="numeric"
placeholder="Enter risk-free rate"
placeholderTextColor="#C7C7CD" //
/>
</View>
<View style={styles.inputContainer}>
<Text style={styles.inputLabel}>Total Amount to Allocate:</Text>
<TextInput
style={styles.input}
value={totalAmount ? String(totalAmount) : ''}
onChangeText={(text) => setTotalAmount(parseFloat(text) || 0)}
keyboardType="numeric"
placeholder="Enter total amount"
placeholderTextColor="#C7C7CD"
/>
</View>
<View style={styles.datePickerContainer}>
<View style={styles.datePicker}>
<Text style={styles.datePickerText}>Select Start Date</Text>
<DateTimePicker
value={startDate}
mode="date"
display="default"
onChange={onChangeStart}
style={styles.datePickerWrapper}
/>
</View>
<View style={styles.datePicker}>
<Text style={styles.datePickerText}>Select End Date</Text>
<DateTimePicker
value={endDate}
mode="date"
display="default"
onChange={onChangeEnd}
style={styles.datePickerWrapper}
/>
</View>
</View>
<Button title="Run Model" onPress={fetchDataAndRunModel} style={styles.runButton} />
</>
)}
ListFooterComponent={() => (
results && (
<View style={styles.resultsContainer}>
<View style={styles.resultCard}>
<View style={styles.resultHeaderContainer}>
<Text style={styles.resultHeader}>Mean Returns %:</Text>
</View>
{results.meanReturns.map((returnVal, index) => (
<Text key={basket[index]} style={styles.resultContent}>
{capitalize(basket[index])}: {returnVal.toFixed(4)}
</Text>
))}
</View>
<View style={styles.resultCard}>
<View style={styles.resultHeaderContainer}>
<Text style={styles.resultHeader}>Max Sharpe Ratio Weights:</Text>
</View>
{results.maxSharpeWeights.map((weight, index) => (
<Text key={basket[index]} style={styles.resultContent}>
{capitalize(basket[index])}: {weight.toFixed(2)}
</Text>
))}
</View>
<View style={styles.resultCard}>
<View style={styles.resultHeaderContainer}>
<Text style={styles.resultHeader}>Equal Risk Contribution (ERC) Weights:</Text>
</View>
{results.ercWeights.map((weight, index) => (
<Text key={basket[index]} style={styles.resultContent}>
{capitalize(basket[index])}: {weight.toFixed(2)}
</Text>
))}
</View>
</View>
)
)}
/>
);
};
export default Home;