-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
479 lines (418 loc) · 18.1 KB
/
Copy pathutils.ts
File metadata and controls
479 lines (418 loc) · 18.1 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
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
import { Stock, Transaction, TransactionType, PortfolioItem, Market, Account, AssetSnapshot, GeneralAssetItem, CashTransaction, CSVSettings } from './types';
// Generate a random ID
export const generateId = (): string => Math.random().toString(36).substring(2, 9);
// Calculate shares held before a specific date
export const getSharesBeforeDate = (stockId: string, targetDate: string, transactions: Transaction[]): number => {
if (!targetDate) return 0;
const normalizeDate = (d: string) => d.replace(/\//g, '-');
const normalizedTarget = normalizeDate(targetDate);
const relevantTxs = transactions.filter(t => {
if (t.stockId !== stockId) return false;
const tDate = normalizeDate(t.date);
return tDate < normalizedTarget && (t.type === TransactionType.BUY || t.type === TransactionType.SELL);
});
let shares = 0;
relevantTxs.forEach(tx => {
if (tx.type === TransactionType.BUY) shares += tx.quantity;
if (tx.type === TransactionType.SELL) shares -= tx.quantity;
});
return shares;
};
// --- New: Independent Stock Performance Calculator (Background Capable) ---
export const calculateStockPerformance = async (
stock: Stock,
startDate: string,
endDate: string
): Promise<{
success: boolean;
startPrice?: number;
endPrice?: number;
dividends?: number;
returnRate?: number;
totalDiff?: number;
error?: string;
actualStartDate?: string;
}> => {
try {
const sDate = new Date(startDate);
const eDate = new Date(endDate);
// Add buffer
const queryStart = new Date(sDate);
queryStart.setDate(sDate.getDate() - 14);
const period1 = Math.floor(queryStart.getTime() / 1000);
const period2 = Math.floor(eDate.getTime() / 1000) + 86400;
// Use '1wk' for very long ranges to avoid truncation
const yearsDiff = (eDate.getTime() - sDate.getTime()) / (1000 * 60 * 60 * 24 * 365);
const interval = yearsDiff > 15 ? '1wk' : '1d';
let symbol = stock.ticker;
if (stock.market === Market.TW && !symbol.includes('.')) symbol += '.TW';
const targetUrl = `https://query1.finance.yahoo.com/v8/finance/chart/${symbol}?period1=${period1}&period2=${period2}&interval=${interval}&events=div|split`;
const proxies = [
(url: string) => `https://corsproxy.io/?${encodeURIComponent(url)}`,
(url: string) => `https://api.allorigins.win/raw?url=${encodeURIComponent(url)}`
];
let data: any = null;
for (const proxy of proxies) {
try {
const res = await fetch(proxy(targetUrl));
if (res.ok) {
data = await res.json();
if (data.chart?.result?.[0]) break;
}
} catch (e) { console.warn('Proxy failed', e); }
}
if (!data?.chart?.result?.[0]) {
if (stock.market === Market.TW && symbol.endsWith('.TW')) {
const otcSymbol = symbol.replace('.TW', '.TWO');
const otcUrl = `https://query1.finance.yahoo.com/v8/finance/chart/${otcSymbol}?period1=${period1}&period2=${period2}&interval=${interval}&events=div|split`;
for (const proxy of proxies) {
try {
const res = await fetch(proxy(otcUrl));
if (res.ok) {
data = await res.json();
if (data.chart?.result?.[0]) break;
}
} catch (e) {}
}
}
}
if (!data?.chart?.result?.[0]) return { success: false, error: 'No Data' };
const result = data.chart.result[0];
const timestamps = result.timestamp || [];
const quotes = result.indicators.quote[0];
const adjCloses = result.indicators.adjclose?.[0]?.adjclose || [];
const divEvents = result.events?.dividends || {};
const splitEvents = result.events?.splits || {};
if (timestamps.length === 0) return { success: false, error: 'Empty Timeline' };
const targetStartTs = sDate.getTime() / 1000;
const targetEndTs = eDate.getTime() / 1000 + 86399;
const toDateStr = (ts: number) => new Date(ts * 1000).toISOString().split('T')[0];
let startIdx = -1;
for(let i=0; i<timestamps.length; i++) {
if (timestamps[i] >= targetStartTs && quotes.close[i] != null) {
startIdx = i; break;
}
}
if (startIdx === -1) startIdx = 0;
let endIdx = -1;
for(let i=timestamps.length-1; i>=0; i--) {
if (timestamps[i] <= targetEndTs && quotes.close[i] != null) {
endIdx = i; break;
}
}
if (endIdx === -1) endIdx = timestamps.length - 1;
if (startIdx > endIdx) startIdx = endIdx;
const actualStartTs = timestamps[startIdx];
const actualStartDate = toDateStr(actualStartTs);
// Always use Adjusted Close for "Performance Record"
const startRaw = quotes.close[startIdx] || 0;
const endRaw = quotes.close[endIdx] || 0;
const startAdj = adjCloses[startIdx] != null ? adjCloses[startIdx] : startRaw;
const endAdj = adjCloses[endIdx] != null ? adjCloses[endIdx] : endRaw;
// Split Logic
const splitsArr = Object.values(splitEvents).map((s: any) => ({
dateStr: toDateStr(s.date),
ts: s.date,
numerator: s.numerator,
denominator: s.denominator,
ratio: s.numerator / s.denominator
})).sort((a: any, b: any) => a.ts - b.ts);
// Dividend Logic (Not strictly needed for ADJ mode calculation but good to have)
let totalDiv = 0;
Object.keys(divEvents).forEach(tsKey => {
const ts = parseInt(tsKey);
const divDateStr = toDateStr(ts);
if (divDateStr >= actualStartDate && ts <= timestamps[endIdx]) {
let rawAmount = divEvents[tsKey].amount;
let adjustmentFactor = 1;
splitsArr.forEach((split: any) => {
if (split.dateStr > divDateStr) {
adjustmentFactor *= split.ratio;
}
});
totalDiv += (rawAmount / adjustmentFactor);
}
});
// Calculate Return (ADJ Mode Logic)
const priceDiff = endAdj - startAdj;
const returnRate = startAdj > 0 ? (priceDiff / startAdj) * 100 : 0;
return {
success: true,
startPrice: startAdj,
endPrice: endAdj,
dividends: 0, // In ADJ mode, dividends are baked into price
returnRate,
totalDiff: priceDiff, // Profit per share
actualStartDate
};
} catch (e: any) {
return { success: false, error: e.message };
}
};
// Calculate Portfolio Status
export const calculatePortfolio = (stocks: Stock[], transactions: Transaction[]): PortfolioItem[] => {
const portfolioMap = new Map<string, PortfolioItem>();
stocks.forEach(stock => {
portfolioMap.set(stock.id, {
stock,
totalShares: 0,
averageCost: 0,
totalCost: 0,
marketValue: 0,
totalDividend: 0,
realizedGain: 0,
unrealizedGain: 0,
unrealizedGainPercent: 0,
totalReturn: 0,
totalReturnPercent: 0
});
});
const sortedTransactions = [...transactions].sort((a, b) => {
const dateA = a.date.replace(/\//g, '-');
const dateB = b.date.replace(/\//g, '-');
return new Date(dateA).getTime() - new Date(dateB).getTime();
});
sortedTransactions.forEach(tx => {
const item = portfolioMap.get(tx.stockId);
if (!item) return;
const fee = tx.fee || 0;
const totalTxAmount = tx.price * tx.quantity;
if (tx.type === TransactionType.BUY) {
// Cost includes Fee
const txCost = totalTxAmount + fee;
const prevTotalCost = item.totalShares * item.averageCost;
const newTotalCost = prevTotalCost + txCost;
const newTotalShares = item.totalShares + tx.quantity;
item.totalShares = newTotalShares;
item.totalCost = newTotalCost;
item.averageCost = newTotalShares > 0 ? newTotalCost / newTotalShares : 0;
} else if (tx.type === TransactionType.SELL) {
// Net Income = Amount - Fee
const netIncome = totalTxAmount - fee;
const costBasis = item.averageCost * tx.quantity;
const gain = netIncome - costBasis;
item.realizedGain += gain;
item.totalShares -= tx.quantity;
item.totalCost -= costBasis;
if (item.totalShares <= 0) {
item.totalShares = 0;
item.totalCost = 0;
item.averageCost = 0;
}
} else if (tx.type === TransactionType.DIVIDEND) {
// Dividend is net (assume fee is handled or input as net)
// Usually user inputs net dividend per share or total.
// If fee exists for dividend, deduct it.
const totalDividend = (tx.price * tx.quantity) - fee;
item.totalDividend += totalDividend;
}
});
return Array.from(portfolioMap.values()).map(item => {
const refPrice = item.stock.currentPrice !== undefined ? item.stock.currentPrice : item.averageCost;
item.marketValue = item.totalShares * refPrice;
item.unrealizedGain = item.marketValue - item.totalCost;
item.unrealizedGainPercent = item.totalCost > 0 ? (item.unrealizedGain / item.totalCost) * 100 : 0;
item.totalReturn = item.realizedGain + item.unrealizedGain + item.totalDividend;
item.totalReturnPercent = item.totalCost > 0 ? (item.totalReturn / item.totalCost) * 100 : 0;
return item;
}).filter(p => p.totalShares > 0 || p.realizedGain !== 0 || p.totalDividend !== 0);
};
// CSV Export (Fully Enhanced)
export const exportToCSV = (
transactions: Transaction[],
stocks: Stock[],
accounts: Account[],
assetHistory: AssetSnapshot[],
generalAssets: GeneralAssetItem[] = [],
cashTransactions: CashTransaction[] = [],
householdTransactions: CashTransaction[] = [],
settings: CSVSettings = {}
) => {
const stockMap = new Map(stocks.map(s => [s.id, s]));
const accountMap = new Map(accounts.map(a => [a.id, a]));
// --- SECTION 1: Stock Transactions (Legacy & Core) ---
// Added '交割日期' (Settlement Date)
const headers = ['日期', '市場(TW/US)', '代號', '名稱', '分類', '交易類別', '每股股息', '股數', '成交價金', '手續費', '總金額', '台幣總金額', '備註', '匯率', '帳戶名稱', '目前市價', '除息日', '配發日', '定期定額', '股利再投入', '帳戶ID', '交割日期'];
const txRows = transactions.map(tx => {
const stock = stockMap.get(tx.stockId);
const accountName = accountMap.get(tx.accountId)?.name || '';
const typeLabel = {
[TransactionType.BUY]: '買進',
[TransactionType.SELL]: '賣出',
[TransactionType.DIVIDEND]: '領息'
}[tx.type];
const dateStr = tx.date.replace(/\//g, '-');
const exDateStr = (tx.exDividendDate || '').replace(/\//g, '-');
const payDateStr = (tx.paymentDate || '').replace(/\//g, '-');
const settlementDateStr = (tx.settlementDate || '').replace(/\//g, '-');
const principal = tx.price * tx.quantity;
const fee = tx.fee || 0;
let totalAmount = principal;
if (tx.type === TransactionType.BUY) totalAmount += fee;
else if (tx.type === TransactionType.SELL) totalAmount -= fee;
const exchangeRate = tx.exchangeRate || 1;
const totalTWD = Math.round(totalAmount * exchangeRate);
const dividendPerShare = tx.type === TransactionType.DIVIDEND ? tx.price : '';
const isDCA = tx.isDCA ? 'Y' : '';
const isDRIP = tx.isDRIP ? 'Y' : '';
return [
dateStr,
stock?.market || '',
stock?.ticker || '',
`"${(stock?.name || '').replace(/"/g, '""')}"`,
`"${(stock?.category || '').replace(/"/g, '""')}"`,
typeLabel,
dividendPerShare,
tx.quantity,
principal,
fee,
totalAmount,
totalTWD,
`"${(tx.note || '').replace(/"/g, '""')}"`,
exchangeRate,
`"${accountName.replace(/"/g, '""')}"`,
stock?.currentPrice || '',
exDateStr,
payDateStr,
isDCA,
isDRIP,
tx.accountId, // Export ID for precise linking
settlementDateStr
].join(',');
});
// --- SECTION 2: Metadata (Stocks/Accounts) ---
const stockRows = stocks.map(s => {
return [
'#系統備份',
s.market,
s.ticker,
`"${s.name.replace(/"/g, '""')}"`,
`"${(s.category || '').replace(/"/g, '""')}"`,
'[股票設定]',
'', '', '', '', '', '',
s.id, // Store Stock ID in '備註' column (Index 12) to preserve it
'', '',
`"${s.currentPrice || ''}"`,
'', '', '', '', '', ''
].join(',');
});
const accountRows = accounts.map(a => {
return [
'#系統備份',
a.id, // Storing ID in '市場' column temporarily for restoration linking
a.isSecurities ? 'Y' : 'N', // Storing Securities flag in '代號'
`"${a.name.replace(/"/g, '""')}"`,
a.isCash ? 'Y' : 'N', // Storing Cash flag in '分類'
'[帳戶設定]',
a.excludeFromTotals ? 'Y' : 'N', // Storing Exclude in '每股股息'
a.linkedCashAccountId || '', // Storing Linked ID in '股數'
'', '', '', '', '', '', '', '', '', '', '', '', '', ''
].join(',');
});
// --- SECTION 3: Asset History ---
const historyHeader = ['#資產趨勢', '日期', '總成本TWD', '總市值TWD', '未實現損益TWD', '除息收益(含息變動)'];
const historyRows = assetHistory.map(h => {
return [
'#資產趨勢',
h.date,
h.totalCostTWD,
h.totalMarketValueTWD,
h.unrealizedPLTWD,
h.todayDividendTWD || 0
].join(',');
});
// --- SECTION 4: General Assets (New) ---
const assetHeader = ['#一般資產', 'ID', '名稱', '類別', '類型', '金額', '連結ID', '排除', '備註', '原始金額', '利率', '還款方式', '月本', '月利', '借款日', '到期日', '銀行', '借款類型', '質押標的ID', '質押張數', '擔保市值'];
const assetRows = generalAssets.map(a => {
return [
'#一般資產',
a.id,
`"${a.name.replace(/"/g, '""')}"`,
a.category,
a.type,
a.value,
a.isLinked ? 'Y' : 'N',
a.isExcluded ? 'Y' : 'N',
`"${(a.note || '').replace(/"/g, '""')}"`,
a.originalAmount || '',
a.interestRate || '',
a.amortizationMethod || '',
a.monthlyPrincipal || '',
a.monthlyInterest || '',
a.loanDate || '',
a.maturityDate || '',
`"${(a.bank || '').replace(/"/g, '""')}"`,
a.loanType || '',
a.targetStockId || '',
a.pledgeLots || '',
a.collateralValue || ''
].join(',');
});
// --- SECTION 5: Cash Transactions (Including Household) ---
const allCashTxs = [...cashTransactions, ...householdTransactions];
const cashHeader = ['#現金收支', 'ID', '日期', '帳戶ID', '類型', '金額', '主類別', '子類別', '備註', '來源ID', '轉出帳戶ID', '轉入帳戶ID', '群組(Household/Invest)'];
const cashRows = allCashTxs.map(c => {
const isHousehold = householdTransactions.some(h => h.id === c.id) ? 'H' : 'I';
return [
'#現金收支',
c.id,
c.date,
c.accountId,
c.type,
c.amount,
`"${(c.category || '').replace(/"/g, '""')}"`,
`"${(c.subCategory || '').replace(/"/g, '""')}"`,
`"${(c.note || '').replace(/"/g, '""')}"`,
c.sourceTransactionId || '',
c.fromAccountId || '',
c.toAccountId || '',
isHousehold
].join(',');
});
// --- SECTION 6: Settings ---
const settingsRows = [];
if (settings.appTitle) settingsRows.push(`#系統設定,APP_TITLE,"${settings.appTitle}"`);
if (settings.autoSyncStartDate) settingsRows.push(`#系統設定,AUTO_SYNC_DATE,${settings.autoSyncStartDate}`);
if (settings.stockOrder) settingsRows.push(`#系統設定,STOCK_ORDER,${settings.stockOrder.join('|')}`);
if (settings.navOrder) settingsRows.push(`#系統設定,NAV_ORDER,${settings.navOrder.join('|')}`);
// Construct CSV Content - Put Metadata FIRST
const csvContent = '\uFEFF' + [
headers.join(','),
...accountRows, // 1. Accounts First
...stockRows, // 2. Stocks Second
...txRows, // 3. Transactions Third
'',
historyHeader.join(','),
...historyRows,
'',
assetHeader.join(','),
...assetRows,
'',
cashHeader.join(','),
...cashRows,
'',
...settingsRows
].join('\n');
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `smartvest_full_export_${new Date().toISOString().split('T')[0]}.csv`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
// CSV Template
export const downloadCSVTemplate = () => {
const headers = ['日期(YYYY-MM-DD)', '市場(TW/US)', '代號', '名稱', '分類(選填)', '交易類別(買進/賣出/領息)', '每股股息(領息用)', '股數', '成交價金(必填)', '手續費(選填)', '總金額', '台幣總金額(選填)', '備註', '匯率(選填)', '帳戶名稱(選填)', '目前市價(選填)', '除息日(選填)', '配發日(選填)', '定期定額(Y/N)', '股利再投入(Y/N)', '帳戶ID(系統用)', '交割日期(選填)'];
const example1 = ['2023-01-15', 'TW', '2330', '台積電', '半導體', '買進', '', '1000', '500000', '20', '500020', '500020', '定期定額扣款', '1', '主帳戶', '580', '', '', 'Y', '', '', '2023-01-17'];
const csvContent = '\uFEFF' + [headers.join(','), example1.join(',')].join('\n');
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'import_template.csv');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};