Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Tests/CoreTests/PortfolioImportTests.swift3// Description: CSV reading and column mapping of a holdings import, valuation by currency, quote batching and rebalancing arithmetic, against hand-computed values.4import Foundation5import Testing6@testable import VQuantCore78@Suite struct PortfolioImportTests {9 @Test func csvRecords() {10 let r = CSVReader.parse("\u{FEFF}a,b,c\r\n1,\"x, y\",\"he said \"\"no\"\"\"\r\n\r\n\"multi\nline\", 2 ,\n")11 #expect(r == [["a", "b", "c"], ["1", "x, y", "he said \"no\""], ["multi\nline", "2", ""]])12 #expect(CSVReader.delimiter(of: "sym;qty;cost\nAAPL;1;2") == ";")13 #expect(CSVReader.delimiter(of: "sym\tqty\nAAPL\t1") == "\t")14 #expect(CSVReader.delimiter(of: "\"a;b\",c\n") == ",")15 #expect(CSVReader.parse("AAPL;10;150,25\nMSFT;5;") == [["AAPL", "10", "150,25"], ["MSFT", "5", ""]])16 #expect(CSVReader.parse("").isEmpty)17 #expect(CSVReader.parse("x") == [["x"]])18 }1920 @Test func numbers() {21 #expect(PortfolioImport.number("1,234.56") == 1234.56)22 #expect(PortfolioImport.number("1 234,56") == 1234.56)23 #expect(PortfolioImport.number("1.234,56") == 1234.56)24 #expect(PortfolioImport.number("12,5") == 12.5)25 #expect(PortfolioImport.number("1,234") == 1234)26 #expect(PortfolioImport.number("0,125") == 0.125)27 #expect(PortfolioImport.number("1,234,567") == 1234567)28 #expect(PortfolioImport.number("(120)") == -120)29 #expect(PortfolioImport.number("-$45.10") == -45.10)30 #expect(PortfolioImport.number("+3") == 3)31 #expect(PortfolioImport.number("abc") == nil)32 #expect(PortfolioImport.number("1.2.3") == nil)33 #expect(PortfolioImport.number("") == nil)34 #expect(PortfolioImport.number("1e5") == nil)35 }3637 @Test func datesAreIsoOnly() {38 var cal = Calendar(identifier: .gregorian); cal.timeZone = TimeZone(identifier: "UTC")!39 let d = PortfolioImport.date("2024-03-15")40 #expect(d.map { cal.dateComponents([.year, .month, .day, .hour], from: $0) } == DateComponents(year: 2024, month: 3, day: 15, hour: 12))41 #expect(PortfolioImport.date("2024/03/15") == d)42 #expect(PortfolioImport.date("2024-03-15T09:30:00Z") == d)43 #expect(PortfolioImport.date("03/15/2024") == nil) // ambiguous forms are refused, not guessed44 #expect(PortfolioImport.date("15.03.2024") == nil)45 #expect(PortfolioImport.date("2024-02-30") == nil)46 #expect(PortfolioImport.date("2024-13-01") == nil)47 }4849 @Test func mappingGuessFromHeader() {50 let i = PortfolioImport(csv: "Ticker,Shares,Avg Cost,Currency,Purchase Date,Notes,Extra\nAAPL,10,150.25,usd,2023-01-05,core,zzz\nmsft,5,,,,,\n")51 #expect(i.hasHeader && i.records.count == 2)52 #expect(i.mapping == [.symbol: 0, .quantity: 1, .costBasis: 2, .currency: 3, .openedAt: 4, .note: 5])53 let rows = i.rows54 #expect(rows.filter(\.isValid).count == 2)55 #expect(rows[0].symbol == "AAPL" && rows[0].quantity == 10 && rows[0].costBasis == 150.25 && rows[0].currency == "USD" && rows[0].note == "core" && rows[0].openedAt != nil)56 #expect(rows[1].symbol == "MSFT" && rows[1].quantity == 5 && rows[1].costBasis == nil && rows[1].currency == nil && rows[1].note == nil)57 // French headers, semicolons, decimal commas58 let f = PortfolioImport(csv: "Symbole;Quantité;Prix moyen;Devise\nSHOP.TO;20;100,50;CAD\n")59 #expect(f.mapping == [.symbol: 0, .quantity: 1, .costBasis: 2, .currency: 3])60 #expect(f.rows[0].costBasis == 100.5 && f.rows[0].symbol == "SHOP.TO")61 // "price" maps to the cost only when nothing better exists; "date" alone is the opened date62 let p = PortfolioImport(csv: "symbol,qty,price,date\nSPY,1,400,2020-01-02\n")63 #expect(p.mapping[.costBasis] == 2 && p.mapping[.openedAt] == 3)64 }6566 @Test func headerlessFileIsPositional() {67 let i = PortfolioImport(csv: "AAPL,10,150\nMSFT,5\n")68 #expect(!i.hasHeader && i.records.count == 2)69 #expect(i.mapping == [.symbol: 0, .quantity: 1, .costBasis: 2])70 #expect(i.validRows.map(\.symbol) == ["AAPL", "MSFT"])71 #expect(i.columnTitle(1) == "Column 2")72 // nothing recognisable: no mapping, every row flagged, nothing importable73 let u = PortfolioImport(csv: "foo,bar\nbaz,qux\n")74 #expect(u.mapping.isEmpty && u.validRows.isEmpty && u.rows.count == 2)75 #expect(u.rows[0].issues.contains("no symbol column"))76 }7778 @Test func invalidRowsAreFlaggedNotDropped() {79 var i = PortfolioImport(csv: "symbol,quantity,cost,currency,date\nAAPL,10,150,USD,2024-01-02\n,5,,,\nMSFT,abc,,,\nNVDA,0,,,\nAAPL,3,,,\nTSLA,2,-4,,\nGOOG,1,10,DOLLARS,03/04/2024\n$$$,1,,,\n")80 let rows = i.rows81 #expect(rows.map(\.isValid) == [true, false, false, false, false, false, true, false])82 #expect(rows[1].issues == ["symbol missing"])83 #expect(rows[2].issues == ["quantity “abc” is not a number"])84 #expect(rows[3].issues == ["quantity is zero"])85 #expect(rows[4].issues == ["duplicate of line 1"])86 #expect(rows[5].issues == ["cost “-4” is not a positive number"])87 #expect(rows[6].warnings.count == 2 && rows[6].currency == nil && rows[6].openedAt == nil)88 #expect(rows[7].issues == ["not a ticker symbol"])89 #expect(i.validRows.map(\.symbol) == ["AAPL", "GOOG"])90 // correcting the mapping by hand changes the reading91 i.mapping[.quantity] = nil92 #expect(i.validRows.isEmpty && i.rows[0].issues == ["no quantity column"])93 }9495 @Test func effectOfMergeAndReplace() {96 let i = PortfolioImport(csv: "symbol,quantity\nAAPL,1\nNVDA,2\nbad,\n")97 let merge = i.effect(on: ["AAPL", "MSFT", "SPY"], mode: .merge)98 #expect(merge.added == 1 && merge.updated == 1 && merge.removed == 0 && merge.kept == 2)99 let replace = i.effect(on: ["AAPL", "MSFT", "SPY"], mode: .replace)100 #expect(replace.added == 1 && replace.updated == 1 && replace.removed == 2 && replace.kept == 0)101 }102103 @Test func valuationNeverAddsCurrencies() {104 let t = Date(timeIntervalSince1970: 1_700_000_000)105 let v = HoldingsValuation(106 holdings: [HoldingInput(symbol: "AAPL", quantity: 10, costBasis: 150), HoldingInput(symbol: "MSFT", quantity: 5, costBasis: 300), HoldingInput(symbol: "SHOP.TO", quantity: 20, costBasis: 100, currency: "USD"),107 HoldingInput(symbol: "ZZZ", quantity: 3, costBasis: 1, currency: "EUR")],108 quotes: ["AAPL": HoldingQuote(price: 200, change: -2, changePct: -1, currency: "USD", asOf: t), "MSFT": HoldingQuote(price: 400, change: 4, changePct: 1, currency: "USD", asOf: t.addingTimeInterval(-60)),109 "SHOP.TO": HoldingQuote(price: 150, change: 1.5, changePct: 1, currency: "CAD", asOf: t)],110 cash: [("cad", 200), ("USD", 1000), ("EUR", 50), ("GBP", 0)], baseCurrency: "CAD")111 #expect(v.groups.map(\.currency) == ["CAD", "USD", "EUR"]) // base first, then by value; a zero balance makes no group112 #expect(!v.isSingleCurrency && v.unpriced == ["ZZZ"])113 let usd = v.groups[1], cad = v.groups[0], eur = v.groups[2]114 #expect(usd.marketValue == 4000 && usd.cash == 1000 && usd.total == 5000 && usd.cost == 3000 && usd.pnl == 1000 && usd.dayChange == 0 && usd.positions == 2)115 #expect(abs((usd.pnlPercent ?? 0) - 33.3333333) < 1e-6)116 // the quote's currency wins over the one recorded on the position117 #expect(cad.marketValue == 3000 && cad.cash == 200 && cad.cost == 2000 && cad.pnl == 1000 && cad.dayChange == 30)118 #expect(abs((cad.dayChangePercent ?? 0) - 30.0 / 2970 * 100) < 1e-9)119 #expect(eur.marketValue == 0 && eur.cash == 50 && eur.positions == 0 && eur.cost == nil)120 // weights are shares of the positions of the same currency121 #expect(v.lines[0].weight == 50 && v.lines[1].weight == 50 && v.lines[2].weight == 100 && v.lines[3].weight == nil)122 #expect(v.lines[3].currency == "EUR" && v.lines[3].marketValue == nil)123 #expect(v.asOf == t.addingTimeInterval(-60))124 }125126 @Test func valuationTotalsNeedEveryCostBasis() {127 let v = HoldingsValuation(holdings: [HoldingInput(symbol: "A", quantity: 1, costBasis: 5), HoldingInput(symbol: "B", quantity: 2)],128 quotes: ["A": HoldingQuote(price: 10, currency: "USD"), "B": HoldingQuote(price: 10, change: 1, currency: "USD")])129 #expect(v.isSingleCurrency && v.groups[0].marketValue == 30 && v.groups[0].cost == nil && v.groups[0].pnl == nil)130 #expect(v.groups[0].dayChange == nil) // one line has no change: no partial sum is shown as the total131 #expect(v.lines[0].pnl == 5 && v.lines[0].pnlPercent == 100 && v.lines[1].pnl == nil)132 // a currency nobody states is its own group, never merged into the base133 let u = HoldingsValuation(holdings: [HoldingInput(symbol: "X", quantity: 1)], quotes: ["X": HoldingQuote(price: 3)])134 #expect(u.groups.map(\.currency) == [HoldingsValuation.unknownCurrency])135 let empty = HoldingsValuation(holdings: [], quotes: [:])136 #expect(empty.groups.isEmpty && empty.isSingleCurrency && empty.asOf == nil)137 }138139 @Test func quoteBatches() {140 let symbols = (1...130).map { "S\($0)" } + ["S1", "", "S2"]141 let b = Batching.chunks(symbols, size: 60)142 #expect(b.map(\.count) == [60, 60, 10] && b[0].first == "S1" && b[2].last == "S130")143 #expect(Batching.chunks([], size: 60).isEmpty)144 }145146 @Test func rebalanceArithmetic() {147 let out = RebalanceMath.apply(units: ["AAPL": 1.5, "SHOP.TO": -20, "TLT": 4, "GLD": 0], to: [("AAPL", 10), ("MSFT", 5), ("SHOP.TO", 20)])148 #expect(out.map(\.symbol) == ["AAPL", "MSFT", "TLT"])149 #expect(out.map(\.quantity) == [11.5, 5, 4])150 }151}152