From 52a71232c05ab14109682b0e5b8d3ee34e9efe0f Mon Sep 17 00:00:00 2001 From: Reed Es Date: Mon, 29 Aug 2022 17:55:27 -0600 Subject: [PATCH] first commit --- .gitignore | 3 + .swift-version | 1 + LICENSE | 373 ++++++++++++++++++ Package.swift | 40 ++ README.md | 38 ++ Sources/Allocation/AllocateUtils.swift | 283 +++++++++++++ Sources/Context/ContextUtils.swift | 129 ++++++ Sources/Context/LowContext.swift | 163 ++++++++ Sources/Core/AllocLowError1.swift | 39 ++ Sources/Core/AllocLowError2.swift | 92 +++++ Sources/Core/BaseParams.swift | 117 ++++++ Sources/Core/LowTypes.swift | 38 ++ Sources/Helpers/AssetValue+Map.swift | 26 ++ Sources/Model/MAccount+Utils.swift | 42 ++ Sources/Model/MAllocation+Utils.swift | 60 +++ Sources/Rebalance/LiquidateHolding.swift | 105 +++++ .../MRebalanceAllocation+Utils.swift | 38 ++ .../Rebalance/MRebalancePurchase+Utils.swift | 32 ++ Sources/Rebalance/MRebalanceSale+Utils.swift | 38 ++ Sources/Rebalance/Purchase.swift | 68 ++++ Sources/Rebalance/RebalanceUtils.swift | 75 ++++ Sources/Rebalance/Sale.swift | 122 ++++++ Sources/Support/AssetValue+Describe.swift | 96 +++++ Sources/Support/DescribeUtils.swift | 166 ++++++++ Sources/Table/BaseColumnHeader.swift | 40 ++ Sources/Table/BaseItem.swift | 53 +++ Sources/Table/BaseRow.swift | 46 +++ Sources/Table/BaseTable.swift | 116 ++++++ Tests/Allocate/AllocMiscTests.swift | 114 ++++++ Tests/Allocate/AllocateGetPercentTests.swift | 82 ++++ Tests/Allocate/AllocateSkewTests.swift | 38 ++ .../Allocate/AllocateUserMaxLimitTests.swift | 232 +++++++++++ Tests/Allocate/GetCapacitiesMapTests.swift | 67 ++++ Tests/Allocate/GetLimitPctMapTests.swift | 62 +++ Tests/Allocate/GetVertLimitsTests.swift | 124 ++++++ Tests/Core/BaseParamsTests.swift | 38 ++ Tests/Model/MHoldingTests.swift | 65 +++ Tests/Rebalance/BaseSaleTests.swift | 111 ++++++ .../GetHoldingsSummaryMapTests.swift | 83 ++++ .../Rebalance/GetLiquidateHoldingsTests.swift | 168 ++++++++ Tests/Rebalance/GetPurchasesTests.swift | 81 ++++ Tests/Rebalance/GetRebalanceMapTests.swift | 344 ++++++++++++++++ Tests/Rebalance/GetSalesTests.swift | 155 ++++++++ Tests/Rebalance/HoldingsSummaryTests.swift | 30 ++ Tests/Rebalance/LiquidateHoldingTests.swift | 70 ++++ .../MRebalancePurchaseMapTests.swift | 84 ++++ Tests/Rebalance/MRebalanceSaleMapTests.swift | 124 ++++++ 47 files changed, 4511 insertions(+) create mode 100644 .gitignore create mode 100644 .swift-version create mode 100644 LICENSE create mode 100644 Package.swift create mode 100644 README.md create mode 100644 Sources/Allocation/AllocateUtils.swift create mode 100644 Sources/Context/ContextUtils.swift create mode 100644 Sources/Context/LowContext.swift create mode 100644 Sources/Core/AllocLowError1.swift create mode 100644 Sources/Core/AllocLowError2.swift create mode 100644 Sources/Core/BaseParams.swift create mode 100644 Sources/Core/LowTypes.swift create mode 100644 Sources/Helpers/AssetValue+Map.swift create mode 100644 Sources/Model/MAccount+Utils.swift create mode 100644 Sources/Model/MAllocation+Utils.swift create mode 100644 Sources/Rebalance/LiquidateHolding.swift create mode 100644 Sources/Rebalance/MRebalanceAllocation+Utils.swift create mode 100644 Sources/Rebalance/MRebalancePurchase+Utils.swift create mode 100644 Sources/Rebalance/MRebalanceSale+Utils.swift create mode 100644 Sources/Rebalance/Purchase.swift create mode 100644 Sources/Rebalance/RebalanceUtils.swift create mode 100644 Sources/Rebalance/Sale.swift create mode 100644 Sources/Support/AssetValue+Describe.swift create mode 100644 Sources/Support/DescribeUtils.swift create mode 100644 Sources/Table/BaseColumnHeader.swift create mode 100644 Sources/Table/BaseItem.swift create mode 100644 Sources/Table/BaseRow.swift create mode 100644 Sources/Table/BaseTable.swift create mode 100644 Tests/Allocate/AllocMiscTests.swift create mode 100644 Tests/Allocate/AllocateGetPercentTests.swift create mode 100644 Tests/Allocate/AllocateSkewTests.swift create mode 100644 Tests/Allocate/AllocateUserMaxLimitTests.swift create mode 100644 Tests/Allocate/GetCapacitiesMapTests.swift create mode 100644 Tests/Allocate/GetLimitPctMapTests.swift create mode 100644 Tests/Allocate/GetVertLimitsTests.swift create mode 100644 Tests/Core/BaseParamsTests.swift create mode 100644 Tests/Model/MHoldingTests.swift create mode 100644 Tests/Rebalance/BaseSaleTests.swift create mode 100644 Tests/Rebalance/GetHoldingsSummaryMapTests.swift create mode 100644 Tests/Rebalance/GetLiquidateHoldingsTests.swift create mode 100644 Tests/Rebalance/GetPurchasesTests.swift create mode 100644 Tests/Rebalance/GetRebalanceMapTests.swift create mode 100644 Tests/Rebalance/GetSalesTests.swift create mode 100644 Tests/Rebalance/HoldingsSummaryTests.swift create mode 100644 Tests/Rebalance/LiquidateHoldingTests.swift create mode 100644 Tests/Rebalance/MRebalancePurchaseMapTests.swift create mode 100644 Tests/Rebalance/MRebalanceSaleMapTests.swift diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0ca9c38 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.build/ +.swiftpm/ +Package.resolved diff --git a/.swift-version b/.swift-version new file mode 100644 index 0000000..c7cb131 --- /dev/null +++ b/.swift-version @@ -0,0 +1 @@ +5.3.1 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a612ad9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/Package.swift b/Package.swift new file mode 100644 index 0000000..cc7103a --- /dev/null +++ b/Package.swift @@ -0,0 +1,40 @@ +// swift-tools-version:5.5 +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import PackageDescription + +let package = Package( + name: "FlowAllocLow", + platforms: [.macOS(.v12), .iOS(.v15)], + products: [ + .library(name: "FlowAllocLow", targets: ["FlowAllocLow"]), + ], + dependencies: [ + .package(url: "https://github.com/openalloc/FlowXCT.git", from: "1.1.0"), + .package(url: "https://github.com/openalloc/FlowBase.git", from: "1.1.0"), + ], + targets: [ + .target( + name: "FlowAllocLow", + dependencies: [ + "FlowBase", + ], + path: "Sources" + ), + .testTarget( + name: "FlowAllocLowTests", + dependencies: [ + "FlowAllocLow", + "FlowBase", + "FlowXCT", + ], + path: "Tests" + ), + ] +) diff --git a/README.md b/README.md new file mode 100644 index 0000000..13eb0e9 --- /dev/null +++ b/README.md @@ -0,0 +1,38 @@ +# FlowAllocLow + +Swift library containing low-level support for the [FlowAllocator](https://openalloc.github.io/FlowAllocator/index.html) app + +_FlowAllocLow_ is part of the [OpenAlloc](https://github.com/openalloc) family of open source Swift software tools. + +## Unit Tests + +Most critical functionality in this library is backed by unit tests. Coverage can likely be better than it is. + +Note that any given unit test may have defects or bad assumptions, and can be worthy of review and re-write. + +## See Also + +* [FlowAllocator](https://openalloc.github.io/FlowAllocator/index.html) - portfolio rebalancing tool for macOS +* [FlowWorth](https://openalloc.github.io/FlowWorth/index.html) - portfolio valuation and tracking tool for macOS +* [FlowUI](https://github.com/openalloc/FlowUI) - shared UI support for the _FlowAllocator_ and _FlowWorth_ apps +* [FlowAllocHigh](https://github.com/openalloc/FlowAllocHigh) - high-level support for the _FlowAllocator_ app +* [FlowAllocLow](https://github.com/openalloc/FlowAllocLow) - low-level support for the _FlowAllocator_ app +* [FlowWorthLib](https://github.com/openalloc/FlowWorthLib) - support for the _FlowWorth_ app +* [FlowBase](https://github.com/openalloc/FlowBase) - shared support for the _FlowAllocator_ and _FlowWorth_ apps +* [FlowStats](https://github.com/openalloc/FlowStats) - shared stats support for the _FlowAllocator_ and _FlowWorth_ apps +* [FlowViz](https://github.com/openalloc/FlowViz) - shared visualization components for the _FlowAllocator_ and _FlowWorth_ apps +* [FlowXCT](https://github.com/openalloc/FlowXCT) - shared testing components for the _FlowAllocator_ and _FlowWorth_ apps + +## License + +Copyright 2021, 2022 OpenAlloc LLC + +The code for this library is licensed under the [Mozilla Public License 2](https://www.mozilla.org/en-US/MPL/2.0/), except where noted in individual modules. + +## Contributing + +Contributions are welcome. You are encouraged to submit pull requests to fix bugs, improve documentation, or offer new features. + +The pull request need not be a production-ready feature or fix. It can be a draft of proposed changes, or simply a test to show that expected behavior is buggy. Discussion on the pull request can proceed from there. + +Contributions should ultimately have adequate test coverage. See tests for current entities to see what coverage is expected. diff --git a/Sources/Allocation/AllocateUtils.swift b/Sources/Allocation/AllocateUtils.swift new file mode 100644 index 0000000..59d110a --- /dev/null +++ b/Sources/Allocation/AllocateUtils.swift @@ -0,0 +1,283 @@ +// +// AllocateUtils.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation +import os + +import AllocData + +import FlowBase + + +let epsilon = 0.0001 // accuracy of Double comparisons + +//let alog = Logger(subsystem: "app.flowallocator", category: "Allocate") + +public func getAccountAllocationMap(allocs: [AssetValue], + accountKeys: [AccountKey], + allocFlowMode: Double, + assetAccountLimitMap: AssetAccountLimitMap, + accountUserVertLimitMap: AccountUserVertLimitMap, + accountUserAssetLimitMap: AccountUserAssetLimitMap, + accountCapacitiesMap: AccountCapacitiesMap, + isStrict: Bool = false) throws -> AccountAssetValueMap +{ + var remainingAssetClassCapacities = allocs.map(\.value) + + let map: AccountAssetValueMap = try accountKeys.enumerated().reduce(into: [:]) { map, entry in + let (accountIndex, accountKey) = entry + + // need to draw this down to 0 for account, or abort allocation (e.g., 33%) + guard let accountCapacity = accountCapacitiesMap[accountKey], + accountCapacity.isGreater(than: 0.0, accuracy: epsilon) + else { + map[accountKey] = [:] // so that cells will be rendered despite no allocation/funds + return + } + + guard let userVertLimitMap = accountUserVertLimitMap[accountKey] else { throw AllocLowError1.missingVertLimit } + guard let userAssetLimitMap = accountUserAssetLimitMap[accountKey] else { throw AllocLowError1.missingAssetLimit } + + map[accountKey] = try getAllocationMap(accountKeys: accountKeys, + accountIndex: accountIndex, + allocs: allocs, + allocFlowMode: allocFlowMode, + accountCapacity: accountCapacity, + assetAccountLimitMap: assetAccountLimitMap, + userVertLimitMap: userVertLimitMap, + userAssetLimitMap: userAssetLimitMap, + remainingAssetClassCapacities: &remainingAssetClassCapacities, + isStrict: isStrict) + } + + return map +} + +func getAllocationMap(accountKeys: [AccountKey], + accountIndex: Int, + allocs: [AssetValue], + allocFlowMode: Double, + accountCapacity: Double, + assetAccountLimitMap: AssetAccountLimitMap, + userVertLimitMap: UserVertLimitMap, + userAssetLimitMap: UserAssetLimitMap, + remainingAssetClassCapacities: inout [Double], + isStrict: Bool = false) throws -> AssetValueMap +{ + // Horizontal: starts as 100% of account's share of strategy, and decreases (vertical) + var remainingToAllocateInAccount = accountCapacity + + return try allocs.enumerated().reduce(into: [:]) { map, entry in + let (allocIndex, alloc) = entry + + guard remainingToAllocateInAccount.isGreater(than: 0.0, accuracy: epsilon) else { return } + + guard let userVertLimit = userVertLimitMap[alloc.assetKey] else { throw AllocLowError1.missingVertLimit } + guard let userAssetLimit = userAssetLimitMap[alloc.assetKey] else { throw AllocLowError1.missingAssetLimit } + let accountLimitMap = assetAccountLimitMap[alloc.assetKey] ?? [:] + + let netAllocation = try getAllocation(accountKeys: accountKeys, + alloc: alloc, + allocIndex: allocIndex, + allocFlowMode: allocFlowMode, + accountCapacity: accountCapacity, + accountLimitMap: accountLimitMap, + accountIndex: accountIndex, + isStrict: isStrict, + userVertLimit: userVertLimit, + userAssetLimit: userAssetLimit, + remainingToAllocateInAccount: remainingToAllocateInAccount, + remainingAssetClassCapacities: &remainingAssetClassCapacities) + + remainingToAllocateInAccount -= netAllocation + + //print("netAllocation=\(netAllocation) remainingToAllocateInAccount=\(remainingToAllocateInAccount)") + + // if less than zero, but within tolerance, coerce to zero, to avoid Core Data + // validation complaining about a negative value. + let netAllocation_ = netAllocation.coerceIfEqual(to: 0.0, accuracy: epsilon) + + map[alloc.assetKey] = netAllocation_ / accountCapacity + } +} + +// returns the size of the allocation, as a fraction of the entire strategy +func getAllocation(accountKeys: [AccountKey], + alloc: AssetValue, + allocIndex: Int, + allocFlowMode: Double, + accountCapacity: Double, + accountLimitMap: AccountLimitMap, + accountIndex: Int, + isStrict: Bool, + userVertLimit: Double, + userAssetLimit: Double, + remainingToAllocateInAccount: Double, + remainingAssetClassCapacities: inout [Double]) throws -> Double +{ + // is the folio's asset class explicitly supported by this account? + // guard let assetID = strategySlice.assetID else { throw StrategySliceError.missingAssetClass } + + // remaining capacity to allocate in current assetID, across subsequent accounts (horizontal) + let remainingAssetClassCapacity = remainingAssetClassCapacities[allocIndex] + + // os_log("[%@] %@ strategySliceIndex=%d remainingAssetClassCapacity=%0.4f", #function, strategySlice.assetID, strategySliceIndex, remainingAssetClassCapacity) + + guard remainingAssetClassCapacity.isGreater(than: 0, accuracy: epsilon) else { return 0 } + + //print("remainingAssetClassCapacities=\(remainingAssetClassCapacities) index=\(strategySliceIndex)") + + // remaining capacity to allocate in subsequent asset classes, across all accounts + let forwardAssetClassCapacity = remainingAssetClassCapacities.forwardSum(start: allocIndex + 1) + + // os_log("[%@] GGG forwardAssetCapacity=%0.4f", #function, forwardAssetClassCapacity) + + // user will tolerate up to 100% of the account to be allocated to an asset class + // e.g., 100% of $64K Roth in SPY + + // calculate the user-suggested limit on allocations for this asset class for all subsequent accounts + // e.g., the user wishes to limit bonds to 0% in the taxable (rightmost) account + let forwardAssetClassLimit: Double = accountLimitMap.forwardSum(order: accountKeys, start: accountIndex + 1) + + //print("forwardAssetClassLimit=\(forwardAssetClassLimit) assetID=\(strategySlice.assetID)") + + // os_log("[%@] HHH forwardAssetClassLimit=%0.4f", #function, forwardAssetClassLimit) + + let skewedAllocFlowMode = getSkewedAllocFlowMode(rawAllocFlowMode: allocFlowMode) + + let flowTarget = getFlowTarget(targetPct: alloc.value, + accountCapacity: accountCapacity, + allocFlowMode: skewedAllocFlowMode) + + let surplusRequired = getSurplusRequired(remainingAssetClassCapacity: remainingAssetClassCapacity, + forwardAssetClassLimit: forwardAssetClassLimit, + flowTarget: flowTarget) + + // suggest a limit for the current cap based on user preference and degree to which we're mirroring + let userMaxLimit = getUserMaxLimit(userLimit: userAssetLimit, + flowTarget: flowTarget, + accountCapacity: accountCapacity, + surplusRequired: surplusRequired) + + // os_log("[%@] cap flowTarget=%0.4f surplusRequired=%0.4f userMaxLimit=%0.4f", #function, flowTarget, surplusRequired, userMaxLimit) + + // limit amount allocated to asset class in account, if specified in allocation slice + let netAllocation = getStrategyPct(remainingAccountCapacity: remainingToAllocateInAccount, + remainingAssetClassCapacity: remainingAssetClassCapacity, + forwardAssetClassCapacity: forwardAssetClassCapacity, + userMaxLimit: userMaxLimit, + userVertLimit: userVertLimit) + + //print("remainingAssetClassCapacity=\(remainingAssetClassCapacity) forwardAssetClassCapacity=\(forwardAssetClassCapacity) forwardAssetClassLimit=\(forwardAssetClassLimit) skewedAllocFlowMode=\(skewedAllocFlowMode) flowTarget=\(flowTarget) surplusRequired=\(surplusRequired) userMaxLimit=\(userMaxLimit) netAllocation=\(netAllocation)") + + if isStrict, netAllocation > userAssetLimit { + throw AllocLowError1.userLimitExceededUnderStrict + } + + // os_log("[%@] MMM netAllocation=%0.4f", #function, netAllocation) + + guard netAllocation.isGreater(than: 0.0, accuracy: epsilon) else { return 0 } + + // for the benefit of future accounts, deduct our current allocation + remainingAssetClassCapacities[allocIndex] -= netAllocation + + // if substantially less than zero, raise the alarm + if netAllocation.isLess(than: 0.0, accuracy: epsilon) { + throw AllocLowError1.unexpectedResult("netSlice less than zero") + } + + return netAllocation +} + +// convex skew for greater sensitivity when adjusting towards flow +func getSkewedAllocFlowMode(rawAllocFlowMode: Double) -> Double { + 1 - ((1 - rawAllocFlowMode) * (1 - rawAllocFlowMode)) +} + +func getFlowTarget(targetPct: Double, + accountCapacity: Double, + allocFlowMode: Double) -> Double +{ + let mirrorTarget = targetPct * accountCapacity + + return mirrorTarget + ((targetPct - mirrorTarget) * allocFlowMode) +} + +func getSurplusRequired(remainingAssetClassCapacity: Double, + forwardAssetClassLimit: Double, + flowTarget: Double) -> Double +{ + max(0, remainingAssetClassCapacity - forwardAssetClassLimit - flowTarget) +} + +// Suggest a limit based on user preference and degree to which we're mirroring. +// +// If mirroring (allocFlowMode<1) for assetID, maximize UP TO current limitPct +// to accommodate user's limitPct on forward allocations in assetID. +// +// With 100% flow (allocFlowMode==1) we're always maximizing to limitPct, so no +// special treatment. +// +func getUserMaxLimit(userLimit: Double, + flowTarget: Double, + accountCapacity: Double, + surplusRequired: Double) -> Double +{ + let baseLimit = min(userLimit, flowTarget) + + return min(accountCapacity, baseLimit + surplusRequired) +} + +// +// In current slice: Example +// - can allocate as most A% 80% +// - must allocate as least B% 10% +// - user wants to allocate at most C% 50% +// +// min( A, max( B, C ) ) 50% +// +// tested in MStrategyTargetGetPercentTests +// +// +func getStrategyPct(remainingAccountCapacity: Double, + remainingAssetClassCapacity: Double, + forwardAssetClassCapacity: Double, + userMaxLimit: Double, + userVertLimit: Double) -> Double +{ + // can allocate at most + let a = min(remainingAccountCapacity, remainingAssetClassCapacity) + + // must allocate at least + let b = max(0, remainingAccountCapacity - forwardAssetClassCapacity) + + // user wants to allocate at most + let c = max(userMaxLimit, userVertLimit) + + return min(a, max(b, c)) +} + +func getCapacitiesMap(_ accountKeys: [AccountKey], + _ accountPresentValueMap: AccountPresentValueMap) -> AccountCapacitiesMap +{ + let accountsTotal = accountKeys.reduce(0) { $0 + (accountPresentValueMap[$1] ?? 0) } + if accountsTotal <= 0 { return AccountCapacitiesMap() } + return accountKeys.reduce(into: [:]) { map, accountKey in + let accountTotal = accountPresentValueMap[accountKey] ?? 0 + map[accountKey] = accountTotal / accountsTotal + } +} + +func getLimitPctMap(_ caps: [MCap]) -> LimitPctMap { + caps.reduce(into: [:]) { map, cap in + guard cap.assetKey.isValid else { return } + map[cap.assetKey] = cap.limitPct + } +} diff --git a/Sources/Context/ContextUtils.swift b/Sources/Context/ContextUtils.swift new file mode 100644 index 0000000..459cb84 --- /dev/null +++ b/Sources/Context/ContextUtils.swift @@ -0,0 +1,129 @@ +// +// ContextUtils.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation + +import FlowBase + + +// horizontal limits +func getAssetAccountLimitMap(accountKeys: [AccountKey], + baseAllocs: [AssetValue], + accountCapacitiesMap: AccountCapacitiesMap, + accountCapsMap: AccountCapsMap) -> AssetAccountLimitMap +{ + guard accountKeys.count == accountCapacitiesMap.count else { + // os_log(.error, "[%@] account:accountCapacities size mismatch (%d != %d) ", #function, accounts.count, accountCapacities.count) + return [:] + } + + return baseAllocs.reduce(into: [:]) { dict, alloc in + + let map: AccountLimitMap = accountKeys.reduce(into: [:]) { map, accountKey in + guard let accountCapacity = accountCapacitiesMap[accountKey] else { return } + + let limitPct: Double = { + let caps = accountCapsMap[accountKey] ?? [] + return caps.first(where: { $0.assetKey == alloc.assetKey })?.limitPct ?? 1.0 + }() + + map[accountKey] = limitPct * accountCapacity + } + + dict[alloc.assetKey] = map + } +} + +func getAccountUserAssetLimitMap(accountKeys: [AccountKey], + baseAllocs: [AssetValue], + accountCapacitiesMap: AccountCapacitiesMap, + accountCapsMap: AccountCapsMap) throws -> AccountUserAssetLimitMap +{ + guard accountKeys.count == accountCapacitiesMap.count else { + // os_log(.error, "[%@] account:accountCapacities size mismatch (%d != %d) ", #function, accounts.count, accountCapacities.count) + return [:] + } + + return accountKeys.reduce(into: [:]) { dict, accountKey in + guard let accountCapacity = accountCapacitiesMap[accountKey] else { return } + + let caps = accountCapsMap[accountKey] ?? [] + let limitPctMap = getLimitPctMap(caps) + + let userAssetLimitMap: UserAssetLimitMap = baseAllocs.reduce(into: [:]) { map, alloc in + + let userLimitAccountPct: Double = limitPctMap[alloc.assetKey] ?? 1.0 + let userLimit: Double = userLimitAccountPct * accountCapacity + + map[alloc.assetKey] = userLimit + } + + dict[accountKey] = userAssetLimitMap + } +} + +// vertical limits +func getAccountUserVertLimitMap(accountKeys: [AccountKey], + baseAllocs: [AssetValue], + accountCapacitiesMap: AccountCapacitiesMap, + accountCapsMap: AccountCapsMap) throws -> AccountUserVertLimitMap +{ + guard accountKeys.count == accountCapacitiesMap.count else { + // os_log(.error, "[%@] account:accountCapacities size mismatch (%d != %d) ", #function, accounts.count, accountCapacities.count) + return [:] + } + + let allocMap = AssetValue.getAssetValueMap(from: baseAllocs) + + return try accountKeys.reduce(into: [:]) { dict, accountKey in + guard let accountCapacity = accountCapacitiesMap[accountKey] else { return } + + let caps = accountCapsMap[accountKey] ?? [] + let limitPctMap = getLimitPctMap(caps) + + dict[accountKey] = try getUserVertLimits(allocMap: allocMap, + limitPctMap: limitPctMap, + accountCapacity: accountCapacity) + } +} + +internal func getUserVertLimits(allocMap: AssetValueMap, + limitPctMap: LimitPctMap, + accountCapacity: Double) throws -> UserVertLimitMap +{ + var restricted_sum = 0.0 + var unrestricted_sum = 0.0 + allocMap.forEach { assetKey, targetPct in + let userLimit = limitPctMap[assetKey] ?? 1.0 + if userLimit <= targetPct { + restricted_sum += userLimit + } else { + unrestricted_sum += targetPct + } + } + + guard restricted_sum + unrestricted_sum > 0 else { throw AllocLowError1.invalidLimits } + + return allocMap.reduce(into: [:]) { map, entry in + let (assetKey, targetPct) = entry + + let userLimit = limitPctMap[assetKey] ?? 1.0 + + let xRatio: Double = { + if userLimit <= targetPct { + return userLimit + } else { + return targetPct / unrestricted_sum * (1 - restricted_sum) + } + }() + + map[assetKey] = xRatio * accountCapacity + } +} diff --git a/Sources/Context/LowContext.swift b/Sources/Context/LowContext.swift new file mode 100644 index 0000000..df5a2df --- /dev/null +++ b/Sources/Context/LowContext.swift @@ -0,0 +1,163 @@ +// +// LowContext.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation + +import AllocData + +import FlowBase + +open class LowContext: BaseContext { + + public override init(_ model: BaseModel, strategyKey: StrategyKey, timestamp: Date = Date(), timeZone: TimeZone = TimeZone.current) { + super.init(model, strategyKey: strategyKey, timestamp: timestamp, timeZone: timeZone) + } + + // return true if context is older than model timestamp (requiring a refresh) + public func isOlderThan(_ modelTimestamp: Date) -> Bool { + updatedAt < modelTimestamp + } + + public lazy var activeAccounts: [MAccount] = { + guard strategyKey.isValid else { return [] } + return model.accounts.filter { $0.strategyKey == strategyKey }.sorted() + }() + + public lazy var activeAccountKeys: [AccountKey] = { + activeAccounts.map(\.primaryKey) + }() + + public lazy var activeAccountKeySet: AccountKeySet = { + Set(activeAccountKeys) + }() + + public lazy var baseAllocs: [AssetValue] = { + guard let allocs = strategyAllocsMap[strategyKey] else { return [] } + return (try? AssetValue.normalize(allocs))?.sorted() ?? [] + }() + + public lazy var strategyAllocationsMap: StrategyAllocationsMap = { + model.strategyAllocationsMap + }() + + public lazy var strategyAllocsMap: StrategyAssetValuesMap = { + model.strategyAllocsMap + }() + + public lazy var baseAllocAssetKeys: [AssetKey] = { + baseAllocs.map(\.assetKey) + }() + + public lazy var baseAccountHoldingsSummaryMap: AccountAssetHoldingsSummaryMap = { + // NOTE should be baseAccountKeys (rather than netAccountKeys) to include fixed accounts in HighContext + HoldingsSummary.getAccountAssetSummaryMap(activeAccountKeys, accountHoldingsMap, securityMap) + }() + + public lazy var baseAccountPresentValueMap: AccountPresentValueMap = { + // NOTE should be activeAccountKeys (rather than netAccountKeys) to include fixed accounts in HighContext + let map = MAccount.getAccountPresentValueMap(activeAccountKeys, accountHoldingsMap, securityMap) + //print(AssetValue.describe(map, prefix: "accountPresentValueMap", style: .currency0)) + return map + }() + + public lazy var baseAllocMap: AssetValueMap = { + AssetValue.getAssetValueMap(from: baseAllocs) + }() + + // MARK: - Overrideable attributes to be used in Allocation + + open var allocatingAccounts: [MAccount] { + activeAccounts + } + + open var allocatingAccountKeys: [AccountKey] { + activeAccountKeys + } + + open var allocatingAllocs: [AssetValue] { + baseAllocs + } + + open var allocatingAllocAssetKeys: [AssetKey] { + baseAllocs.map(\.assetKey) + } + + // MARK: - convenience functions + + public func getAccount(_ key: AccountKey?) -> MAccount? { + guard let key_ = key else { return nil } + return accountMap[key_] + } + + public func getAsset(_ key: AssetKey?) -> MAsset? { + guard let key_ = key else { return nil } + return assetMap[key_] + } + + public func getSecurity(_ key: SecurityKey?) -> MSecurity? { + guard let key_ = key else { return nil } + return securityMap[key_] + } + + public func getStrategy(_ key: StrategyKey?) -> MStrategy? { + guard let key_ = key, + key_.isValid + else { return nil } + return strategyMap[key_] + } + + public func getTracker(_ key: TrackerKey?) -> MTracker? { + guard let key_ = key else { return nil } + return trackerMap[key_] + } + + // MARK: - Flow Allocation Support + + public lazy var accountCapsMap: AccountCapsMap = { + model.capsMap + }() + + public lazy var assetAccountLimitMap: AssetAccountLimitMap = { + getAssetAccountLimitMap(accountKeys: allocatingAccountKeys, + baseAllocs: allocatingAllocs, + accountCapacitiesMap: accountCapacitiesMap, + accountCapsMap: accountCapsMap) + }() + + public lazy var accountUserVertLimitMap: AccountUserVertLimitMap = { + guard let map = try? getAccountUserVertLimitMap(accountKeys: allocatingAccountKeys, + baseAllocs: allocatingAllocs, + accountCapacitiesMap: accountCapacitiesMap, + accountCapsMap: accountCapsMap) + else { return AccountUserVertLimitMap() } + return map + }() + + public lazy var accountUserAssetLimitMap: AccountUserAssetLimitMap = { + guard let map = try? getAccountUserAssetLimitMap(accountKeys: allocatingAccountKeys, + baseAllocs: allocatingAllocs, + accountCapacitiesMap: accountCapacitiesMap, + accountCapsMap: accountCapsMap) + else { return AccountUserAssetLimitMap() } + return map + }() + + public lazy var accountCapacitiesMap: AccountCapacitiesMap = { + getCapacitiesMap(allocatingAccountKeys, + baseAccountPresentValueMap) + }() + + // should include both fixed and allocating (aka variable), but not inactive + public lazy var baseAccountAssetHoldingsMap: AccountAssetHoldingsMap = { + MHolding.getAccountAssetHoldingsMap(accountKeys: activeAccountKeys, + accountHoldingsMap, + securityMap) + }() +} diff --git a/Sources/Core/AllocLowError1.swift b/Sources/Core/AllocLowError1.swift new file mode 100644 index 0000000..6319d4a --- /dev/null +++ b/Sources/Core/AllocLowError1.swift @@ -0,0 +1,39 @@ +// +// AllocLowError1.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation + +//TODO combine with AllocLowError2 +public enum AllocLowError1: Error, Equatable, CustomStringConvertible { + case invalidFlowValues(_ msg: String) + case unableToGetMidpoint + case invalidLimits + case unexpectedResult(_ msg: String) + case userLimitExceededUnderStrict + case missingVertLimit + case missingAssetLimit + + public var localizedDescription: String { description } + + public var description: String { + switch self { + case let .invalidFlowValues(msg): + return String("Invalid flow values: \(msg)") + case let .unexpectedResult(msg): + return String("Unexpected result: \(msg)") + case .unableToGetMidpoint: + return String("Unable to calculate midpoint.") + case .invalidLimits: + return String("Must allow non-zero allocation in account.") + default: + return String("Other error.") + } + } +} diff --git a/Sources/Core/AllocLowError2.swift b/Sources/Core/AllocLowError2.swift new file mode 100644 index 0000000..618cbae --- /dev/null +++ b/Sources/Core/AllocLowError2.swift @@ -0,0 +1,92 @@ +// +// AllocatLowError2.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation + +import AllocData + +import FlowBase + + +//TODO combine with AllocLowError1 +public enum AllocLowError2: Error, Equatable, CustomStringConvertible { + case generalFailure(_ msg: String) + case invalidContext(_ msg: String) // TODO: _ implicit param name + case invalidConfig(_ msg: String) + case invalidParams(_ msg: String) + case invalidShareCount(_ shareCount: Double) + case invalidSharePrice(_ sharePrice: Double) + case invalidShareBasis(_ shareBasis: Double) + case invalidTransactedAt(_ transactedAt: String) + case missingAssetClassForSecurity(_ securityID: String) + case unrecognizedAccount(_ accountID: AccountID) + case unrecognizedSecurity(_ security: MSecurity) + case encodingError(_ msg: String) + case decodingError(_ msg: String) + case decodingKeyError(key: String, classType: String, _ msg: String) + case importError(_ msg: String) + case exportError(_ msg: String) + case rejectedDuplicate(_ msg: String) + case missingContext(_ msg: String) + case missingStrategy(_ msg: String) + case summarizationFailure + case invalidStorageKey(_ key: String) + + public var localizedDescription: String { description } + + public var description: String { + switch self { + case let .generalFailure(msg): + return String(msg) + case let .invalidContext(msg): + return String("Invalid context: \(msg)") + case let .invalidConfig(msg): + return String("Invalid config: \(msg)") + case let .invalidParams(msg): + return String("Invalid params: \(msg)") + + case let .invalidShareCount(val): + return String("Invalid share count: \(val.format2()).") + case let .invalidSharePrice(val): + return String("Invalid share price: \(val.format2()).") + case let .invalidShareBasis(val): + return String("Invalid share price: \(val.format2()).") + case let .invalidTransactedAt(val): + return String("Invalid share price: \(val).") + + case let .missingAssetClassForSecurity(securityID): + return String("Missing asset class for security '\(securityID)'.") + case let .unrecognizedAccount(accountID): + return String("Accounts does not contain '\(accountID)'.") + case let .unrecognizedSecurity(security): + return String("Securities does not contain '\(security)'.") + case let .encodingError(msg): + return String("Failure to encode. \(msg)") + case let .decodingError(msg): + return String("Failure to decode. \(msg)") + case let .decodingKeyError(key, classType, msg): + return String("Failure to decode '\(key)' in \(classType). \(msg)") + case let .importError(msg): + return String("Failure to import. \(msg)") + case let .exportError(msg): + return String("Failure to export. \(msg)") + case let .rejectedDuplicate(msg): + return String("Rejected duplicate. \(msg)") + case let .missingContext(msg): + return String("Missing context. \(msg)") + case let .missingStrategy(msg): + return String("Missing strategy. \(msg)") + case .summarizationFailure: + return String("Unable to summarize results of allocation.") + case let .invalidStorageKey(key): + return String("Invalid storage key '\(key)'.") + } + } +} diff --git a/Sources/Core/BaseParams.swift b/Sources/Core/BaseParams.swift new file mode 100644 index 0000000..733092a --- /dev/null +++ b/Sources/Core/BaseParams.swift @@ -0,0 +1,117 @@ +// +// BaseParams.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation + +import FlowBase +import AllocData + +public struct BaseParams: Hashable, Codable, CustomStringConvertible { + public var accountKeys: [AccountKey] + public var assetKeys: [AssetKey] + public var flowMode: Double + public var isStrict: Bool + public var fixedAccountKeys: [AccountKey] + + public init(accountKeys: [AccountKey] = [], + assetKeys: [AssetKey] = [], + flowMode: Double = 0.0, + isStrict: Bool = false, + fixedAccountKeys: [AccountKey] = []) + { + self.accountKeys = accountKeys + self.assetKeys = assetKeys + self.flowMode = flowMode + self.isStrict = isStrict + self.fixedAccountKeys = fixedAccountKeys + } + + private enum CodingKeys: String, CodingKey, CaseIterable { + case accountKeys + case assetKeys + case flowMode + case isStrict + case fixedAccountKeys + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + accountKeys = try c.decode([MAccount.Key].self, forKey: .accountKeys) + assetKeys = try c.decode([MAsset.Key].self, forKey: .assetKeys) + flowMode = try c.decode(Double.self, forKey: .flowMode) + isStrict = try c.decode(Bool.self, forKey: .isStrict) + fixedAccountKeys = try c.decode([MAccount.Key].self, forKey: .fixedAccountKeys) + } + + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(accountKeys, forKey: .accountKeys) + try c.encode(assetKeys, forKey: .assetKeys) + try c.encode(flowMode, forKey: .flowMode) + try c.encode(isStrict, forKey: .isStrict) + try c.encode(fixedAccountKeys, forKey: .fixedAccountKeys) + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(accountKeys) + hasher.combine(assetKeys) + hasher.combine(flowMode) + hasher.combine(isStrict) + hasher.combine(fixedAccountKeys) + } + + public func validate(epsilon: Double = 0.0001) throws { + guard accountKeys.count > 0 else { throw AllocLowError2.invalidParams("missing accounts") } + guard assetKeys.count > 0 else { throw AllocLowError2.invalidParams("missing allocation") } + guard (0.0 ... 1.0).contains(flowMode) else { throw AllocLowError2.invalidParams("flowMode must be in range 0...1 [\(description)]") } + } + + public var description: String { + ["accountKeys: \(accountKeys))", + "assetKeys: \(assetKeys))"].joined(separator: "; ") + } + + // update with new indexes, trying to preserve order where possible + mutating public func update(nuAccountKeys: [AccountKey], + nuAssetKeys: [AssetKey], + nuFixedAccountKeys: [AccountKey]) + { + if Set(nuAccountKeys) != Set(accountKeys) { + //print("flowParams: updating \(nuAccountKeys)") + accountKeys = nuAccountKeys + } + + if Set(nuAssetKeys) != Set(assetKeys) { + //print("flowParams: updating \(nuAssetKeys)") + assetKeys = nuAssetKeys + } + + if Set(nuFixedAccountKeys) != Set(fixedAccountKeys) { + //print("surgeParams: updating \(nuFixedAccountKeys)") + fixedAccountKeys = nuFixedAccountKeys + } + } +} + +extension BaseParams: Equatable { + public static func == (lhs: BaseParams, rhs: BaseParams) -> Bool { + lhs.accountKeys == rhs.accountKeys && + lhs.assetKeys == rhs.assetKeys && + lhs.flowMode == rhs.flowMode && + lhs.isStrict == rhs.isStrict && + lhs.fixedAccountKeys == rhs.fixedAccountKeys + } +} + +extension BaseParams: Comparable { + public static func < (lhs: BaseParams, rhs: BaseParams) -> Bool { + lhs.flowMode < rhs.flowMode + } +} diff --git a/Sources/Core/LowTypes.swift b/Sources/Core/LowTypes.swift new file mode 100644 index 0000000..0ee9920 --- /dev/null +++ b/Sources/Core/LowTypes.swift @@ -0,0 +1,38 @@ +// +// LowTypes.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import AllocData + +import FlowBase + + +public typealias AccountAmountMap = [AccountKey: Double] +public typealias AccountAssetValueMap = [AccountKey: AssetValueMap] +public typealias AccountCapacitiesMap = [AccountKey: Double] +public typealias AccountCapsMap = [AccountKey: [MCap]] +public typealias AccountPresentValueMap = [AccountKey: Double] +public typealias AccountPurchasesMap = [AccountKey: [Purchase]] +public typealias AccountRebalanceMap = [AccountKey: RebalanceMap] +public typealias AccountSalesMap = [AccountKey: [Sale]] +public typealias AccountUserAssetLimitMap = [AccountKey: UserAssetLimitMap] +public typealias AccountUserVertLimitMap = [AccountKey: UserVertLimitMap] +public typealias AllocationMap = [AssetKey: MAllocation] +public typealias AccountLimitMap = [AccountKey: Double] +public typealias AssetAccountLimitMap = [AssetKey: AccountLimitMap] +public typealias AssetTickerMap = [AssetKey: SecurityKeySet] +public typealias LimitPctMap = [AssetKey: Double] +public typealias PurchaseMap = [AssetKey: Purchase] +public typealias RebalanceMap = [AssetKey: Double] +public typealias SaleMap = [AssetKey: Sale] +public typealias SecurityAssetMap = [SecurityKey: AssetKey] +public typealias StrategyAllocationsMap = [StrategyKey: [MAllocation]] +public typealias StrategyAssetValuesMap = [StrategyKey: [AssetValue]] +public typealias UserAssetLimitMap = [AssetKey: Double] +public typealias UserVertLimitMap = [AssetKey: Double] diff --git a/Sources/Helpers/AssetValue+Map.swift b/Sources/Helpers/AssetValue+Map.swift new file mode 100644 index 0000000..0b8893f --- /dev/null +++ b/Sources/Helpers/AssetValue+Map.swift @@ -0,0 +1,26 @@ +// +// AssetValue+Map.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation + +import FlowBase + +public extension AssetValue { + // raw allocations (non-rolled up) + static func getStrategyAssetValuesMap(_ strategyAllocationsMap: StrategyAllocationsMap) -> StrategyAssetValuesMap { // [StrategyKey: [AssetValue]] + let strategyKeys = strategyAllocationsMap.map(\.key) + let allocArrays: [[AssetValue]] = strategyKeys.map { + let allocations = strategyAllocationsMap[$0] ?? [] + return getAssetValues(allocations: allocations) + } + return Dictionary(uniqueKeysWithValues: zip(strategyKeys, allocArrays)) + } + +} diff --git a/Sources/Model/MAccount+Utils.swift b/Sources/Model/MAccount+Utils.swift new file mode 100644 index 0000000..d4462b6 --- /dev/null +++ b/Sources/Model/MAccount+Utils.swift @@ -0,0 +1,42 @@ +// +// MAccount+Utils.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation + +import AllocData + +import FlowBase + +public extension MAccount { + func getCaps(_ model: BaseModel) -> [MCap] { + model.caps.filter { self.primaryKey == $0.accountKey } + } +} + +public extension BaseModel { + // obtain a map of Caps, grouped by account + var capsMap: AccountCapsMap { + Dictionary(grouping: caps, by: { $0.accountKey }) + } +} + +public extension MAccount { + static func getPresentValue(_ accountKey: AccountKey, _ accountHoldingsMap: AccountHoldingsMap, _ securityMap: SecurityMap) -> Double { + guard let holdings = accountHoldingsMap[accountKey] else { return 0 } + return holdings.reduce(0) { $0 + ($1.getPresentValue(securityMap) ?? 0) } + } + + static func getAccountPresentValueMap(_ accountKeys: [AccountKey], _ accountHoldingsMap: AccountHoldingsMap, _ securityMap: SecurityMap) -> AccountPresentValueMap { + let presentValues: [Double] = accountKeys.map { + getPresentValue($0, accountHoldingsMap, securityMap) + } + return Dictionary(uniqueKeysWithValues: zip(accountKeys, presentValues)) + } +} diff --git a/Sources/Model/MAllocation+Utils.swift b/Sources/Model/MAllocation+Utils.swift new file mode 100644 index 0000000..dbe31fe --- /dev/null +++ b/Sources/Model/MAllocation+Utils.swift @@ -0,0 +1,60 @@ +// +// MAllocation+Utils.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation + +import AllocData + +import FlowBase + +public extension MAllocation { + + private static func getAllocations(strategyKey: StrategyKey, + allocations: [MAllocation], + filteredBy assetKeys: AssetKeySet) -> [MAllocation] + { + allocations.filter { + strategyKey.isValid && + $0.strategyKey == strategyKey && + $0.assetKey.isValid && + assetKeys.contains($0.assetKey) && + $0.targetPct > 0 + } + } +} + +public extension MAllocation { + static func getAllocMap(allocations: [MAllocation]) -> AssetValueMap { + let assetKeys = allocations.map(\.assetKey) + let targetPcts = allocations.map(\.targetPct) + return Dictionary(uniqueKeysWithValues: zip(assetKeys, targetPcts)) + } + + static func getAllocMap(strategyKey: StrategyKey, + allocations: [MAllocation], + filteredBy assetKeySet: AssetKeySet) -> AssetValueMap + { + let tuples: [(AssetKey, Double)] = getAllocations(strategyKey: strategyKey, allocations: allocations, filteredBy: assetKeySet).compactMap { + guard $0.assetKey.isValid else { return nil } + return ($0.assetKey, $0.targetPct) + } + return Dictionary(uniqueKeysWithValues: tuples) + } +} + +public extension BaseModel { + var strategyAllocationsMap: StrategyAllocationsMap { // [StrategyKey: [MAllocation]] + Dictionary(grouping: allocations, by: { $0.strategyKey }) + } + + var strategyAllocsMap: StrategyAssetValuesMap { // [StrategyKey: [AssetValue]] + AssetValue.getStrategyAssetValuesMap(strategyAllocationsMap) + } +} diff --git a/Sources/Rebalance/LiquidateHolding.swift b/Sources/Rebalance/LiquidateHolding.swift new file mode 100644 index 0000000..93d8382 --- /dev/null +++ b/Sources/Rebalance/LiquidateHolding.swift @@ -0,0 +1,105 @@ +// +// LiquidateHolding.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation + +import AllocData + +import FlowBase + + +// representing all (fraction=1) or part of a holding (fraction<1) to liquidate +public struct LiquidateHolding: Hashable, Encodable { + public let holding: MHolding + public let presentValue: Double + public let fraction: Double + + public init(_ holding: MHolding, presentValue: Double, fraction: Double = 1.0) { + self.holding = holding + self.presentValue = presentValue + self.fraction = fraction + } + + public var securityKey: SecurityKey { + holding.securityKey + } + + public var absoluteShareCount: Double { + holding.shareCount ?? 0.0 + } + + public var fractionalShareCount: Double { + absoluteShareCount * fraction + } + + public var fractionalValue: Double? { + presentValue * fraction + } + + public var sharePrice: Double { + presentValue / absoluteShareCount + } + + public var fractionalGainLoss: Double? { + guard let shareBasis_ = holding.shareBasis else { return nil } + return (presentValue - (absoluteShareCount * shareBasis_)) * fraction + } +} + +extension LiquidateHolding: Comparable { + public static func < (lhs: LiquidateHolding, rhs: LiquidateHolding) -> Bool { + (lhs.fractionalValue ?? 0) < (rhs.fractionalValue ?? 0) + } +} + +extension LiquidateHolding: Equatable { + public static func == (lhs: LiquidateHolding, rhs: LiquidateHolding) -> Bool { + lhs.holding == rhs.holding && + lhs.fraction == rhs.fraction + } +} + +extension LiquidateHolding { + public func getTicker(_ securityMap: SecurityMap) -> SecurityID? { + guard securityKey.isValid else { return nil } + return securityMap[securityKey]?.securityID + } + + // NOTE that holdings SHOULD have been sorted in getAssetHoldingsMap by gainLoss (asc) + // to avoid having to re-sort here. + static func getLiquidations(_ securityMap: SecurityMap, + _ holdings: [MHolding], + _ remainingToSell: inout Double, + _ minimumPositionValue: Double = 0) -> [LiquidateHolding] + { + holdings.compactMap { holding in + + guard remainingToSell > 0, + let pv = holding.getPresentValue(securityMap), + pv > 0 + else { return nil } + + var amountToSell = min(pv, remainingToSell) + + let remainingPositionValue = pv - amountToSell + + // avoid leaving tiny positions behind + if remainingPositionValue.isLessThanOrEqual(to: minimumPositionValue, accuracy: epsilon) { + amountToSell = pv + } + + remainingToSell -= min(remainingToSell, amountToSell) + + let fractionToSell = amountToSell / pv // 1.0 is selling all of holding + + return .init(holding, presentValue: pv, fraction: fractionToSell) + } + } +} diff --git a/Sources/Rebalance/MRebalanceAllocation+Utils.swift b/Sources/Rebalance/MRebalanceAllocation+Utils.swift new file mode 100644 index 0000000..db8948a --- /dev/null +++ b/Sources/Rebalance/MRebalanceAllocation+Utils.swift @@ -0,0 +1,38 @@ +// +// MRebalanceAllocation+Utils.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation + +import AllocData + +import FlowBase + + +public extension MRebalanceAllocation { + + static func getAllocations(_ accountKeys: [AccountKey], + _ accountAmountMap: AccountAmountMap, + _ accountAllocMap: AccountAssetValueMap, + _ accountMap: AccountMap, + _ assetMap: AssetMap) -> [MRebalanceAllocation] { + accountKeys.reduce(into: []) { array, accountKey in + guard let account = accountMap[accountKey], + let assetValueMap = accountAllocMap[accountKey] + else { return } + let mallocations: [MRebalanceAllocation] = assetValueMap.compactMap { + guard let assetID = assetMap[$0.key]?.assetID, + let presentValue = accountAmountMap[accountKey] else { return nil } + let amount = $0.value * presentValue + return MRebalanceAllocation(accountID: account.accountID, assetID: assetID, amount: amount) + } + array.append(contentsOf: mallocations) + } + } +} diff --git a/Sources/Rebalance/MRebalancePurchase+Utils.swift b/Sources/Rebalance/MRebalancePurchase+Utils.swift new file mode 100644 index 0000000..1128443 --- /dev/null +++ b/Sources/Rebalance/MRebalancePurchase+Utils.swift @@ -0,0 +1,32 @@ +// +// MRebalancePurchase+Utils.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation + +import AllocData + +import FlowBase + + +public extension MRebalancePurchase { + + static func getPurchases(_ accountPurchasesMap: AccountPurchasesMap, _ accountMap: AccountMap, _ assetMap: AssetMap) -> [MRebalancePurchase] { + accountPurchasesMap.reduce(into: []) { array, entry in + let (accountKey, purchases) = entry // [AccountKey: [Purchase]] + guard let account = accountMap[accountKey] else { return } + let mpurchases: [MRebalancePurchase] = purchases.compactMap { + guard let assetID = assetMap[$0.assetKey]?.assetID else { return nil } + return MRebalancePurchase(accountID: account.accountID, assetID: assetID, amount: $0.amount) + } + array.append(contentsOf: mpurchases) + } + } + +} diff --git a/Sources/Rebalance/MRebalanceSale+Utils.swift b/Sources/Rebalance/MRebalanceSale+Utils.swift new file mode 100644 index 0000000..d3543c3 --- /dev/null +++ b/Sources/Rebalance/MRebalanceSale+Utils.swift @@ -0,0 +1,38 @@ +// +// MRebalanceSale+Utils.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation + +import AllocData + +import FlowBase + + +public extension MRebalanceSale { + + static func getSales(_ accountSalesMap: AccountSalesMap) -> [MRebalanceSale] { + accountSalesMap.reduce(into: []) { array, entry in + let (_, sales) = entry // [AccountKey: [Sale]] + sales.forEach { sale in + sale.liquidateHoldings.forEach { lh in + guard let amount = lh.fractionalValue else { return } + let msale = MRebalanceSale(accountID: lh.holding.accountID, + securityID: lh.holding.securityID, + lotID: lh.holding.lotID, + amount: amount, + shareCount: lh.fractionalShareCount, + liquidateAll: lh.fraction.isEqual(to: 1.0, accuracy: 0.001)) + array.append(msale) + } + } + } + } + +} diff --git a/Sources/Rebalance/Purchase.swift b/Sources/Rebalance/Purchase.swift new file mode 100644 index 0000000..c0ff565 --- /dev/null +++ b/Sources/Rebalance/Purchase.swift @@ -0,0 +1,68 @@ +// +// Purchase.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation + +import FlowBase +import AllocData + + +public struct Purchase: Hashable, Identifiable { + public let id = UUID() + + // asset class of new holding to purchase + public var assetKey: AssetKey + + // amount to purchase/liquidate, in currency + public let amount: Double + + public init(assetKey: AssetKey, amount: Double) { + self.assetKey = assetKey + self.amount = amount + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(assetKey) + hasher.combine(amount) + // super.hash(into: &hasher) + } + + public static func getPurchaseMap(rebalanceMap: RebalanceMap) -> PurchaseMap + { + let purchases = getPurchases(rebalanceMap: rebalanceMap) + let assetKeys = purchases.map(\.assetKey) + return Dictionary(uniqueKeysWithValues: zip(assetKeys, purchases)) + } + + public static func getPurchases(rebalanceMap: RebalanceMap) -> [Purchase] { + let epsilon = 0.01 // nearest 'penny' + + let acquisitions: [Purchase] = rebalanceMap.sorted(by: { $0.key < $1.key }).compactMap { assetKey, amount in + + // ignore near-zero purchases, cash purchases, and all sales + guard amount.isGreater(than: 0, accuracy: epsilon), + assetKey != MAsset.cashAssetKey + else { return nil } + + return Purchase(assetKey: assetKey, + amount: amount) + } + + // order by amount desc + return acquisitions.sorted(by: { $0.amount > $1.amount }) + } +} + +extension Purchase: Equatable { + public static func == (lhs: Purchase, rhs: Purchase) -> Bool { + lhs.assetKey == rhs.assetKey && + lhs.amount == rhs.amount + } +} diff --git a/Sources/Rebalance/RebalanceUtils.swift b/Sources/Rebalance/RebalanceUtils.swift new file mode 100644 index 0000000..14d3c45 --- /dev/null +++ b/Sources/Rebalance/RebalanceUtils.swift @@ -0,0 +1,75 @@ +// +// RebalanceUtils.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation +import os + +import FlowBase +import AllocData + +public func getAccountRebalanceMap(accountKeys: [AccountKey], + accountAllocMap: AccountAssetValueMap, + accountHoldingsSummaryMap: AccountAssetHoldingsSummaryMap) -> AccountRebalanceMap +{ + accountKeys.reduce(into: [:]) { map, accountKey in + guard let allocMap = accountAllocMap[accountKey], + let holdingsSummaryMap = accountHoldingsSummaryMap[accountKey] + else { return } + + // total presentValue for holdings in all asset classes for the account + let holdingsPresentValue = holdingsSummaryMap.values.reduce(0) { $0 + $1.presentValue } + + map[accountKey] = getRebalanceMap(allocMap, + holdingsSummaryMap, + holdingsPresentValue) + } +} + +// ORIGINAL - FAST! (1.72s) +public func getRebalanceMap(_ allocMap: AssetValueMap, + _ holdingsSummaryMap: AssetHoldingsSummaryMap, + _ holdingsPresentValue: Double) -> RebalanceMap +{ + let amountEpsilon: Double = 0.001 // within nearest tenth of 'penny' + + var zPairs = [(AssetKey, Double)]() + zPairs.reserveCapacity(allocMap.count) + + func transact(assetKey: AssetKey, targetAmount: Double, holdingValue: Double) { + // positive: purchase/acquire + // negative: sale/liquidate + let diff = targetAmount - holdingValue + + if diff.isNotEqual(to: 0, accuracy: amountEpsilon) { + zPairs.append((assetKey, diff)) + } + } + + for (assetKey, targetPct) in allocMap { + guard assetKey != MAsset.cashAssetKey else { continue } + + transact(assetKey: assetKey, + targetAmount: targetPct * holdingsPresentValue, + holdingValue: holdingsSummaryMap[assetKey]?.presentValue ?? 0) + } + + // sell off the orphans + for (assetKey, holdingsSummary) in holdingsSummaryMap { + guard allocMap[assetKey] == nil, + assetKey != MAsset.cashAssetKey + else { continue } + + transact(assetKey: assetKey, + targetAmount: 0, + holdingValue: holdingsSummary.presentValue) + } + + return Dictionary(uniqueKeysWithValues: zPairs) +} diff --git a/Sources/Rebalance/Sale.swift b/Sources/Rebalance/Sale.swift new file mode 100644 index 0000000..eae37d1 --- /dev/null +++ b/Sources/Rebalance/Sale.swift @@ -0,0 +1,122 @@ +// +// Sale.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation + +import FlowBase +import AllocData + +public struct Sale: Hashable, Identifiable { + + public let id = UUID() + + public static let epsilon = 0.01 // nearest 'penny' + + // asset class of holdings to liquidate + public var assetKey: AssetKey + + // the amount we're targeting to liquidate (should be positive) + public let targetAmount: Double + + // the MHolding(accountID: "", securityID: s) to liquidate, at least in part + public var liquidateHoldings: [LiquidateHolding] = [] + + public init(assetKey: AssetKey, targetAmount: Double, liquidateHoldings: [LiquidateHolding] = []) { + self.liquidateHoldings = liquidateHoldings + self.assetKey = assetKey + self.targetAmount = targetAmount + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(assetKey) + hasher.combine(targetAmount) + hasher.combine(liquidateHoldings) + } +} + +extension Sale: Equatable { + public static func == (lhs: Sale, rhs: Sale) -> Bool { + lhs.assetKey == rhs.assetKey && + lhs.targetAmount == rhs.targetAmount && + lhs.liquidateHoldings == rhs.liquidateHoldings + } +} + +public extension Sale { + var tickerKeys: [SecurityKey] { + Set(liquidateHoldings.map(\.holding.securityKey)).sorted() + } + + var proceeds: Double { + liquidateHoldings.reduce(0) { $0 + ($1.fractionalValue ?? 0) } + } + + var netGainLoss: Double { + liquidateHoldings.reduce(0) { $0 + ($1.fractionalGainLoss ?? 0) } + } + + // absolute gains (ignoring all losses) + var absoluteGains: Double { + liquidateHoldings.reduce(0) { $0 + max(0, $1.fractionalGainLoss ?? 0) } + } +} + +public extension Sale { + static func getSaleMap(_ rebalanceMap: AssetValueMap, + _ assetHoldingsMap: AssetHoldingsMap, + _ securityMap: SecurityMap, + //_ cashAssetKeySet: AssetKeySet, + minimumSaleAmount: Double = 0, + minimumPositionValue: Double = 0) -> SaleMap + { + let sales = getSales(rebalanceMap, + assetHoldingsMap, + securityMap, + //cashAssetKeySet, + minimumSaleAmount: minimumSaleAmount, + minimumPositionValue: minimumPositionValue) + let assetKeys = sales.map(\.assetKey) + return Dictionary(uniqueKeysWithValues: zip(assetKeys, sales)) + } + + static func getSales(_ rebalanceMap: AssetValueMap, // won't be grouped + _ assetHoldingsMap: AssetHoldingsMap, // will be grouped if 'Group Related Assets' is enabled + _ securityMap: SecurityMap, + minimumSaleAmount: Double = 0, + minimumPositionValue: Double = 0) -> [Sale] + { + rebalanceMap.sorted(by: { $0.key < $1.key }).compactMap { assetKey, rawAmount in + + // ignore near-zero sales, cash sales, and all purchases + guard rawAmount.isLess(than: 0, accuracy: epsilon), + assetKey != MAsset.cashAssetKey + else { return nil } + + let amount = -1 * rawAmount // flip the negative sale amount to positive + + guard amount >= minimumSaleAmount else { return nil } + + var remainingToSell = amount + + guard let qualifyingHoldings = assetHoldingsMap[assetKey], + qualifyingHoldings.count > 0 + else { return nil } + + let liquidations = LiquidateHolding.getLiquidations(securityMap, + qualifyingHoldings, + &remainingToSell, + minimumPositionValue) + + return .init(assetKey: assetKey, + targetAmount: amount, + liquidateHoldings: liquidations) + } + } +} diff --git a/Sources/Support/AssetValue+Describe.swift b/Sources/Support/AssetValue+Describe.swift new file mode 100644 index 0000000..247650d --- /dev/null +++ b/Sources/Support/AssetValue+Describe.swift @@ -0,0 +1,96 @@ +// +// AssetValue+Describe.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation + +import FlowBase +import AllocData + +public extension AssetValue { + enum DescribeStyle { + case percent0 + case percent1 + case percent2 + case currency0 + case currency2 + case format0 + case format1 + case format2 + case format3 + case general + } + + // single AssetValue struct + static func describe(_ av: AssetValue, style: DescribeStyle = .general) -> String { + let formattedValue = format(av.value, style: style) + return "\(av.assetKey): \(formattedValue)" + } + + static func format(_ value: Double, style: DescribeStyle = .general) -> String { + switch style { + case .percent0: + return value.percent0() + case .percent1: + return value.percent1() + case .percent2: + return value.percent2() + case .currency0: + return value.currency0() + case .currency2: + return value.currency2() + case .format0: + return value.format0() + case .format1, .general: + return value.format1() + case .format2: + return value.format2() + case .format3: + return value.format3() + } + } + + // array of AssetValue structs + static func describe(_ assetValues: [AssetValue], prefix: String? = nil, style: DescribeStyle = .general) -> String { + let formattedValues = assetValues.sorted().map { describe($0, style: style) } + let formattedValuesJoined = formattedValues.joined(separator: ", ") + if let prefix_ = prefix { + let formattedSum = format(sumOf(assetValues), style: style) + return "\(prefix_) [\(formattedSum)]: \(formattedValuesJoined)" + } + return formattedValuesJoined + } + + // dictionary of AssetValue structs, keyed by String + static func describe(_ assetValueDict: [String: AssetValue], prefix: String? = nil, style: DescribeStyle = .general, separator: String = "; ") -> String { + let formattedValues: [String] = assetValueDict.sorted(by: { $0.key < $1.key }).reduce(into: []) { array, entry in + array.append("\(entry.key): \(AssetValue.describe(entry.value, style: style))") + } + let formattedValuesJoined = formattedValues.joined(separator: separator) + if let prefix_ = prefix { + let formattedSum = format(sumOf(assetValueDict), style: style) + return "\(prefix_) [\(formattedSum)]: \(formattedValuesJoined)" + } + return formattedValuesJoined + } + + // single AssetValueMap, or [AssetKey: Value] + static func describe(_ assetValueMap: AssetValueMap, prefix: String? = nil, style: DescribeStyle = .general) -> String { + let formattedValues: [String] = assetValueMap.sorted(by: { $0.key < $1.key }).reduce(into: []) { array, entry in + let av = AssetValue(entry.key, entry.value) + array.append(AssetValue.describe(av, style: style)) + } + let formattedValuesJoined = formattedValues.joined(separator: ", ") + if let prefix_ = prefix { + let formattedSum = format(sumOf(assetValueMap), style: style) + return "\(prefix_) [\(formattedSum)]: \(formattedValuesJoined)" + } + return formattedValuesJoined + } +} diff --git a/Sources/Support/DescribeUtils.swift b/Sources/Support/DescribeUtils.swift new file mode 100644 index 0000000..1982bf0 --- /dev/null +++ b/Sources/Support/DescribeUtils.swift @@ -0,0 +1,166 @@ +// +// DescribeUtils.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation + +import FlowBase +import AllocData + +public func describe(_ map: AccountAssetHoldingsSummaryMap, _ prefix: String) -> String { + var buffer = [String]() + + for (accountID, hMap) in map.sorted(by: { $0.key < $1.key }) { + buffer.append("\(accountID) => { \(describe(hMap)) }") + } + + return "\(prefix) " + buffer.joined(separator: "; ") +} + +public func describe(_ dict: AssetHoldingsSummaryMap) -> String { + let ordered = dict.sorted(by: { $0.key < $1.key }) // key, ascending + return ordered.map { "‘\($0.0)’: \($0.1)" }.joined(separator: ", ") +} + +// Compound: 100232.10 (23%), 2323.13 (10%), ... +public func describe(total: Double, _ dict: [AssetKey: Double], _ prefix: String? = nil, orderByValue: Bool = true) -> String { + let formatter: (Double) -> (String) = { "\((total * $0).currency0()) (\($0.percent1()))" } + return describe(dict, prefix, orderByValue: orderByValue, formatter: formatter) +} + +public func describe(_ dict: [AssetKey: Double], prefix: String? = nil, orderByValue: Bool = true, percent: Bool = false) -> String { + let formatter: (Double) -> (String) = percent ? { $0.percent1() } : { $0.currency0() } + return describe(dict, prefix, orderByValue: orderByValue, formatter: formatter) +} + +private func describe(_ dict: [AssetKey: Double], _ prefix: String?, orderByValue: Bool, formatter: (Double) -> (String)) -> String { + let ordered = orderByValue + ? dict.sorted(by: { $0.value > $1.value || ($0.value == $1.value && $0.key < $1.key) }) // value, descending + : dict.sorted(by: { $0.key < $1.key }) // key, ascending + // let ordered2 = ordered.filter({ $0.1 != 0 }) + let suffix = ordered.map { "\($0.0): \(formatter($0.1))" }.joined(separator: ", ") + let total = formatter(dict.values.reduce(0) { $0 + $1 }) + let suffix2 = "(\(ordered.count) @ \(total)) => \(suffix)" + if let prefix_ = prefix { + return "\(prefix_) \(suffix2)" + } + return suffix2 +} + + +public func describe(_ map: AssetHoldingsMap, _ securityMap: SecurityMap, _ prefix: String? = nil) -> String { + var buffer = [String]() + + for (assetKey, holdings) in map.sorted(by: { $0.key < $1.key }) { + buffer.append("\(assetKey) => [\n\t\(MHolding.describe(holdings, securityMap, separator: ",\n\t"))]") + } + + let formattedValuesJoined = buffer.joined(separator: "\n") + if let prefix_ = prefix { + return "\(prefix_): \(formattedValuesJoined)" + } + return formattedValuesJoined +} + +public func describe(_ map: [AssetKey: AssetKey], _ prefix: String? = nil) -> String { + let suffix = map.sorted(by: { $0.key < $1.key }).map { "(\($0) -> \($1))" }.joined(separator: ", ") + let suffix2 = "(\(map.count)) => \(suffix)" + if let prefix_ = prefix { + return "\(prefix_) \(suffix2)" + } + return suffix2 +} + +public func describe(_ assetClasses: AssetKeySet, _ prefix: String? = nil) -> String { + describe(Array(assetClasses), prefix) +} + +public func describe(_ assetClasses: [AssetKey], _ prefix: String? = nil) -> String { + let suffix = assetClasses.map { "\($0)" }.sorted(by: { $0 < $1 }).joined(separator: ", ") + let suffix2 = "(\(assetClasses.count)) => \(suffix)" + if let prefix_ = prefix { + return "\(prefix_) \(suffix2)" + } + return suffix2 +} + +public func describe(_ himap: AssetHoldingsSummaryMap, _ prefix: String? = nil) -> String { + let suffix = himap.map { "\($0): \($1)" }.sorted(by: { $0 < $1 }).joined(separator: ", ") + if let prefix_ = prefix { + return "\(prefix_) \(suffix)" + } + return suffix +} + +public func describe(_ assetClassLimitMap: AssetAccountLimitMap, prefix: String? = nil) -> String { + let suffix = assetClassLimitMap.sorted(by: { $0.key < $1.key }) + .map { "\($0.key): (\($0.value.map { "\($0.key): \($0.value.percent1())" }.joined(separator: ", ")))" } + .joined(separator: "; ") + if let prefix_ = prefix { + return "\(prefix_) \(suffix)" + } + return suffix +} + +public func describe(accountUserVertLimitMap: AccountUserVertLimitMap, prefix: String? = nil) -> String { + let suffix = accountUserVertLimitMap.sorted(by: { $0.key < $1.key }) + .map { "\($0.key): \(describe($0.value, percent: true))" } + .joined(separator: "; ") + if let prefix_ = prefix { + return "\(prefix_) \(suffix)" + } + return suffix +} + +public func describe(accountUserAssetLimitMap: AccountUserAssetLimitMap, prefix: String? = nil) -> String { + let suffix = accountUserAssetLimitMap.sorted(by: { $0.key < $1.key }) + .map { "\($0.key): \(describe($0.value, percent: true))" } + .joined(separator: "; ") + if let prefix_ = prefix { + return "\(prefix_) \(suffix)" + } + return suffix +} + + +public func describe(accountAssetValueMap: AccountAssetValueMap, prefix: String? = nil) -> String { + let suffix = accountAssetValueMap.sorted(by: { $0.key < $1.key }) + .map { "\($0.key): \(describe($0.value, percent: true))" } + .joined(separator: "; ") + if let prefix_ = prefix { + return "\(prefix_) \(suffix)" + } + return suffix +} + + +public func describe(_ accounts: [MAccount], _ prefix: String? = nil) -> String { + // : \($0.holdings.count) holdings @ \($0.holdingsPresentValue.currency0()) + let suffix = accounts.map { "\($0.title ?? "") (\($0.accountID))" }.joined(separator: "; ") + // let total = accounts.reduce(0) { $0 + $1.holdingsPresentValue }.currency0() + let suffix2 = suffix // (\(accounts.count) @ \(total)) => \(suffix)" + if let prefix_ = prefix { + return "\(prefix_) \(suffix2)" + } + return suffix2 +} + +private func describe(_ dict: [String: Double], _ prefix: String?, orderByValue: Bool = true, formatter: (Double) -> (String)) -> String { + let ordered = orderByValue + ? dict.sorted(by: { $0.value > $1.value || ($0.value == $1.value && $0.key < $1.key) }) // value, descending + : dict.sorted(by: { $0.key < $1.key }) // key, ascending + // let ordered2 = ordered.filter({ $0.1 != 0 }) + let suffix = ordered.map { "\($0.0): \(formatter($0.1))" }.joined(separator: ", ") + let total = formatter(dict.values.reduce(0) { $0 + $1 }) + let suffix2 = "(\(ordered.count) @ \(total)) => \(suffix)" + if let prefix_ = prefix { + return "\(prefix_) \(suffix2)" + } + return suffix2 +} diff --git a/Sources/Table/BaseColumnHeader.swift b/Sources/Table/BaseColumnHeader.swift new file mode 100644 index 0000000..6ac4204 --- /dev/null +++ b/Sources/Table/BaseColumnHeader.swift @@ -0,0 +1,40 @@ +// +// BaseColumnHeader.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation + +import AllocData + +import FlowBase + +open class BaseColumnHeader: Identifiable, Hashable { + public var id: Int { hashValue } + public var account: MAccount + public var accountValue: Double + public var fractionOfStrategy: Double + + public init(account: MAccount, accountValue: Double, fractionOfStrategy: Double) { + self.account = account + self.accountValue = accountValue + self.fractionOfStrategy = fractionOfStrategy + } + + open func hash(into hasher: inout Hasher) { + hasher.combine(account) + hasher.combine(accountValue) + hasher.combine(fractionOfStrategy) + } +} + +extension BaseColumnHeader: Equatable { + public static func == (lhs: BaseColumnHeader, rhs: BaseColumnHeader) -> Bool { + lhs.account == rhs.account + } +} diff --git a/Sources/Table/BaseItem.swift b/Sources/Table/BaseItem.swift new file mode 100644 index 0000000..563387b --- /dev/null +++ b/Sources/Table/BaseItem.swift @@ -0,0 +1,53 @@ +// +// BaseItem.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation + +import FlowBase + + +// need unique values to populate LazyVGrid, so this wrapper used +open class BaseItem: Hashable, Identifiable { + public var id: Int { hashValue } + public var accountKey: AccountKey + public var holdingsSummary: HoldingsSummary + public var allocatedValue: Double + public var colorCode: Int + + public var alloc: AssetValue + + public init(accountKey: AccountKey, + alloc: AssetValue, + holdingsSummary: HoldingsSummary, + allocatedValue: Double, + colorCode: Int) + { + self.accountKey = accountKey + self.alloc = alloc + self.holdingsSummary = holdingsSummary + self.allocatedValue = allocatedValue + self.colorCode = colorCode + } + + open func hash(into hasher: inout Hasher) { + hasher.combine(accountKey) + hasher.combine(alloc) + hasher.combine(holdingsSummary) + hasher.combine(allocatedValue) + hasher.combine(colorCode) + } +} + +extension BaseItem: Equatable { + public static func == (lhs: BaseItem, rhs: BaseItem) -> Bool { + lhs.accountKey == rhs.accountKey && + lhs.alloc == rhs.alloc + } +} diff --git a/Sources/Table/BaseRow.swift b/Sources/Table/BaseRow.swift new file mode 100644 index 0000000..b466d58 --- /dev/null +++ b/Sources/Table/BaseRow.swift @@ -0,0 +1,46 @@ +// +// BaseRow.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation + +import FlowBase + + +open class BaseRow: Hashable, Identifiable { + public var id: Int { hashValue } + public var assetKey: AssetKey + public var targetPct: Double + public var allocatedValue: Double + public var cells: [BaseItem] + public var colorCode: Int + + public init(assetKey: AssetKey, targetPct: Double, allocatedValue: Double, cells: [BaseItem], colorCode: Int) { + self.assetKey = assetKey + self.targetPct = targetPct + self.allocatedValue = allocatedValue + self.cells = cells + self.colorCode = colorCode + } + + open func hash(into hasher: inout Hasher) { + // hasher.combine(id) + hasher.combine(assetKey) + hasher.combine(targetPct) + hasher.combine(allocatedValue) + hasher.combine(cells) + hasher.combine(colorCode) + } +} + +extension BaseRow: Equatable { + public static func == (lhs: BaseRow, rhs: BaseRow) -> Bool { + lhs.assetKey == rhs.assetKey + } +} diff --git a/Sources/Table/BaseTable.swift b/Sources/Table/BaseTable.swift new file mode 100644 index 0000000..e331327 --- /dev/null +++ b/Sources/Table/BaseTable.swift @@ -0,0 +1,116 @@ +// +// BaseTable.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import Foundation + +import AllocData + +import FlowBase + + +open class BaseTable { + public var context: LowContext? + public var params: BaseParams // contains ordering of accounts and assetclasses + public var accountAllocMap: AccountAssetValueMap + + public init(context: LowContext?, + params: BaseParams, + accountAllocMap: AccountAssetValueMap) + { + self.context = context + self.params = params + self.accountAllocMap = accountAllocMap + } + + open var accounts: [MAccount] { + guard let ax = context else { return [] } + return ax.activeAccounts + } + + open var allocs: [AssetValue] { + guard let ax = context else { return [] } + return ax.baseAllocs + } + + open var rows: [BaseRow] { + guard let ax = context else { return [] } + + let totalValue = ax.baseAccountPresentValueMap.values.reduce(0) { $0 + $1 } + + return assetKeyTargetPcts.map { assetKey, targetPct in + + let colorCode = ax.colorCodeMap[assetKey] ?? 0 + + let allocationItems: [BaseItem] = accountKeyAllocationMaps.map { accountKey, allocMap in + + let allocatedPct = allocMap[assetKey] ?? 0 + let alloc = AssetValue(assetKey, allocatedPct) + let accountValue = ax.baseAccountPresentValueMap[accountKey] ?? 0 + let allocatedValue = accountValue * allocatedPct + + let holdingsSummaryMap = ax.baseAccountHoldingsSummaryMap[accountKey] ?? [:] + let holdingsSummary = holdingsSummaryMap[assetKey] ?? HoldingsSummary() + + return BaseItem(accountKey: accountKey, + alloc: alloc, + holdingsSummary: holdingsSummary, + allocatedValue: allocatedValue, + colorCode: colorCode) + } + + let allocatedTotalValue = targetPct * totalValue + + return BaseRow(assetKey: assetKey, + targetPct: targetPct, + allocatedValue: allocatedTotalValue, + cells: allocationItems, + colorCode: colorCode) + } + } + + open var headerCells: [BaseColumnHeader] { + guard let ax = context else { return [] } + let totalValue = ax.baseAccountPresentValueMap.values.reduce(0) { $0 + $1 } + let orderedAccounts = params.accountKeys.compactMap { ax.strategiedAccountMap[$0] } + return orderedAccounts.map { + let accountValue = ax.baseAccountPresentValueMap[$0.primaryKey] ?? 0 + return BaseColumnHeader(account: $0, + accountValue: accountValue, + fractionOfStrategy: accountValue / totalValue) + } + } + + private var assetKeyTargetPcts: [(AssetKey, Double)] { + guard let ax = context else { return [] } + let assetKeys = params.assetKeys + let targetPcts = assetKeys.compactMap { ax.baseAllocMap[$0] } + return Array(zip(assetKeys, targetPcts)) + } + + private var accountKeyAllocationMaps: [(AccountKey, AssetValueMap)] { + let accountKeys = params.accountKeys + let maps: [AssetValueMap] = accountKeys.compactMap { accountAllocMap[$0] } + return Array(zip(accountKeys, maps)) + } +} + +extension BaseTable: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(params) + hasher.combine(accountAllocMap) + } +} + +extension BaseTable: Equatable { + public static func == (lhs: BaseTable, rhs: BaseTable) -> Bool { + lhs.params == rhs.params && + lhs.accountAllocMap == rhs.accountAllocMap + } +} diff --git a/Tests/Allocate/AllocMiscTests.swift b/Tests/Allocate/AllocMiscTests.swift new file mode 100644 index 0000000..e30cc5c --- /dev/null +++ b/Tests/Allocate/AllocMiscTests.swift @@ -0,0 +1,114 @@ +// +// AllocMiscTests.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import XCTest + +import FlowBase +import AllocData +import FlowXCT + +@testable import FlowAllocLow + +final class AllocMiscTests: XCTestCase { + + let bond = MAsset.Key(assetID: "Bond") + let lc = MAsset.Key(assetID: "LC") + let cash = MAsset.Key(assetID: "Cash") + let gold = MAsset.Key(assetID: "Gold") + + func testBasic() throws { + let accountsCSV = """ + accountID,title,isTaxable,canTrade + 1003,CashMgmt,true,false + 1001,Brokerage,true,true + 1002,IRA,false,true + """ + + let allocationsCSV = """ + allocationStrategyID,allocationAssetID,targetPct,isLocked + MyAlloc,LC,0.5,false + MyAlloc,Bond,0.3,false + MyAlloc,Gold,0.1,false + MyAlloc,Cash,0.1,false + """ + + let strategiesCSV = """ + strategyID,title + MyAlloc,My Portfolio Allocation + """ + + let assetsCSV = """ + assetID,title,colorCode,parentAssetID + LC,Large Cap Blend,137,Total + Bond,Aggregate Bonds,125, + Gold,Gold,117, + Cash,Cash & Cash Equivalent,120, + Total,Total Market,136, + """ + + let holdingsCSV = """ + holdingAccountID,holdingSecurityID,holdingLotID,shareCount,shareBasis,acquiredAt + 1003,CORE,,7500.0,1.0 + 1001,IAU,,220.0,34.0 + 1001,SPY,,87.0,430.0 + 1001,AGG,,194.0,116.0 + 1002,GLD,,15.0,168.0 + 1002,VOO,,31.0,396.0 + 1002,BND,,87.0,86.0 + """ + + let securitiesCSV = """ + securityID,securityAssetID,sharePrice,updatedAt,securityTrackerID + CORE,Cash,1.0,2021-07-08, + IAU,Gold,34.0,2021-07-08, + SPY,LC,430.0,2021-07-08, + AGG,Bond,116.0,2021-07-08, + GLD,Gold,168.0,2021-07-08, + VOO,LC,396.0,2021-07-08, + BND,Bond,86.0,2021-07-08, + """ + + var model = BaseModel() + + //var rr = [AllocRowed.DecodedRow]() + for csv in [accountsCSV, allocationsCSV, strategiesCSV, assetsCSV, holdingsCSV, securitiesCSV] { + _ = try model.detectDecodeImport(data: csv.data(using: .utf8)!, url: URL(fileURLWithPath: "foo.csv")) + } + + let allocs = AssetValue.getAssetValues(allocations: model.allocations) + let flowMode = 0.0 // mirror + let account1 = MAccount.Key(accountID: "1001") + let account2 = MAccount.Key(accountID: "1002") + let accountKeys = [account2, account1] //activeAccounts.map(\.primaryKey) + let accountHoldingsMap = model.makeAccountHoldingsMap() + let securityMap = model.makeSecurityMap() + let accountPVMap = MAccount.getAccountPresentValueMap(accountKeys, accountHoldingsMap, securityMap) + let capacitiesMap = getCapacitiesMap(accountKeys, accountPVMap) + let assetAccountLimitMap = getAssetAccountLimitMap(accountKeys: accountKeys, baseAllocs: allocs, accountCapacitiesMap: capacitiesMap, accountCapsMap: [:]) + let vertLimitMap = try getAccountUserVertLimitMap(accountKeys: accountKeys, baseAllocs: allocs, accountCapacitiesMap: capacitiesMap, accountCapsMap: [:]) + let userLimitMap = try getAccountUserAssetLimitMap(accountKeys: accountKeys, baseAllocs: allocs, accountCapacitiesMap: capacitiesMap, accountCapsMap: [:]) + + let actual = try getAccountAllocationMap(allocs: allocs, + accountKeys: accountKeys, + allocFlowMode: flowMode, + assetAccountLimitMap: assetAccountLimitMap, + accountUserVertLimitMap: vertLimitMap, + accountUserAssetLimitMap: userLimitMap, + accountCapacitiesMap: capacitiesMap) + + let expected = [ + account1: [ lc: 0.5, gold: 0.1, cash: 0.1, bond: 0.3 ], + account2: [ lc: 0.5, gold: 0.1, cash: 0.1, bond: 0.3 ] + ] + + XCTAssertEqual(expected[account1]!, actual[account1]!, accuracy: 0.0001) + XCTAssertEqual(expected[account2]!, actual[account2]!, accuracy: 0.0001) + } +} diff --git a/Tests/Allocate/AllocateGetPercentTests.swift b/Tests/Allocate/AllocateGetPercentTests.swift new file mode 100644 index 0000000..a69c491 --- /dev/null +++ b/Tests/Allocate/AllocateGetPercentTests.swift @@ -0,0 +1,82 @@ +// +// AllocateGetPercentTests.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// +// + +import XCTest + +import FlowBase +import AllocData + +@testable import FlowAllocLow + +class AllocateGetPercentTests: XCTestCase { + func testNothingToDo() { + let pct = getStrategyPct(remainingAccountCapacity: 0.0, + remainingAssetClassCapacity: 0.75, + forwardAssetClassCapacity: 0.2, + userMaxLimit: 1.0, userVertLimit: 0) + + XCTAssertEqual(pct, 0.0, accuracy: 0.001) + } + + func testMaximalSliceAllocation() { + let pct = getStrategyPct(remainingAccountCapacity: 0.5, + remainingAssetClassCapacity: 0.75, + forwardAssetClassCapacity: 0.2, + userMaxLimit: 1.0, userVertLimit: 0) + + XCTAssertEqual(pct, 0.5, accuracy: 0.001) + } + + func testIgnoreUserLimit() { + let pct = getStrategyPct(remainingAccountCapacity: 0.5, + remainingAssetClassCapacity: 0.75, + forwardAssetClassCapacity: 0.2, + userMaxLimit: 0.0, userVertLimit: 0) + + XCTAssertEqual(pct, 0.3, accuracy: 0.001) + } + + func testLimitedByExhaustedSlice() { + let pct = getStrategyPct(remainingAccountCapacity: 0.5, + remainingAssetClassCapacity: 0.41, + forwardAssetClassCapacity: 0.2, + userMaxLimit: 1.0, userVertLimit: 0) + + XCTAssertEqual(pct, 0.41, accuracy: 0.001) + } + + func testRespectUserLimit() { + let pct = getStrategyPct(remainingAccountCapacity: 0.5, + remainingAssetClassCapacity: 0.75, + forwardAssetClassCapacity: 0.5, + userMaxLimit: 0.1, userVertLimit: 0) + + XCTAssertEqual(pct, 0.1, accuracy: 0.001) + } + + func testRespectUserVertLimit() { + let pct = getStrategyPct(remainingAccountCapacity: 0.5, + remainingAssetClassCapacity: 0.75, + forwardAssetClassCapacity: 0.5, + userMaxLimit: 0.1, userVertLimit: 0.15) + + XCTAssertEqual(pct, 0.15, accuracy: 0.001) //TODO is this correct? + } + + func testLastSliceOverrideUser() { + let pct = getStrategyPct(remainingAccountCapacity: 0.5, + remainingAssetClassCapacity: 0.75, + forwardAssetClassCapacity: 0.0, + userMaxLimit: 0.0, userVertLimit: 0) + + XCTAssertEqual(pct, 0.5, accuracy: 0.001) + } +} diff --git a/Tests/Allocate/AllocateSkewTests.swift b/Tests/Allocate/AllocateSkewTests.swift new file mode 100644 index 0000000..2e85f93 --- /dev/null +++ b/Tests/Allocate/AllocateSkewTests.swift @@ -0,0 +1,38 @@ +// +// AllocateSkewTests.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import XCTest + +import FlowBase +import AllocData + +@testable import FlowAllocLow + +class AllocateSkewTests: XCTestCase { + func testSkew() { + let pairs: [(Double, Double)] = [ + (0.0, 0.0), + (0.1, 0.19), + (0.2, 0.36), + (0.3, 0.51), + (0.4, 0.64), + (0.5, 0.75), + (0.6, 0.84), + (0.7, 0.91), + (0.8, 0.96), + (0.9, 0.99), + (1.0, 1.0), + ] + + for pair in pairs { + XCTAssertEqual(pair.1, getSkewedAllocFlowMode(rawAllocFlowMode: pair.0), accuracy: 0.01) + } + } +} diff --git a/Tests/Allocate/AllocateUserMaxLimitTests.swift b/Tests/Allocate/AllocateUserMaxLimitTests.swift new file mode 100644 index 0000000..6c80389 --- /dev/null +++ b/Tests/Allocate/AllocateUserMaxLimitTests.swift @@ -0,0 +1,232 @@ +// +// AllocateUserMaxLimitTests.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// +// + +import XCTest + +import FlowBase +import AllocData + +@testable import FlowAllocLow + +class AllocateUserMaxLimitTests: XCTestCase { + func testGetFlowTarget() { + XCTAssertEqual(0, getFlowTarget(targetPct: 0, accountCapacity: 0, allocFlowMode: 0)) + XCTAssertEqual(0, getFlowTarget(targetPct: 0, accountCapacity: 0, allocFlowMode: 1)) + XCTAssertEqual(0, getFlowTarget(targetPct: 0, accountCapacity: 1, allocFlowMode: 0)) + XCTAssertEqual(0, getFlowTarget(targetPct: 0, accountCapacity: 1, allocFlowMode: 1)) + XCTAssertEqual(0, getFlowTarget(targetPct: 1, accountCapacity: 0, allocFlowMode: 0)) + XCTAssertEqual(1, getFlowTarget(targetPct: 1, accountCapacity: 0, allocFlowMode: 1)) + XCTAssertEqual(1, getFlowTarget(targetPct: 1, accountCapacity: 1, allocFlowMode: 1)) + + XCTAssertEqual(0, getFlowTarget(targetPct: 0, accountCapacity: 0, allocFlowMode: 0.5)) + XCTAssertEqual(0, getFlowTarget(targetPct: 0, accountCapacity: 0.5, allocFlowMode: 0)) + XCTAssertEqual(0, getFlowTarget(targetPct: 0, accountCapacity: 0.5, allocFlowMode: 0.5)) + XCTAssertEqual(0, getFlowTarget(targetPct: 0.5, accountCapacity: 0, allocFlowMode: 0)) + XCTAssertEqual(0.25, getFlowTarget(targetPct: 0.5, accountCapacity: 0, allocFlowMode: 0.5)) + XCTAssertEqual(0.375, getFlowTarget(targetPct: 0.5, accountCapacity: 0.5, allocFlowMode: 0.5)) + + XCTAssertEqual(0.703, getFlowTarget(targetPct: 0.75, accountCapacity: 0.75, allocFlowMode: 0.75), accuracy: 0.001) + XCTAssertEqual(0.656, getFlowTarget(targetPct: 0.75, accountCapacity: 0.75, allocFlowMode: 0.5), accuracy: 0.001) + XCTAssertEqual(0.375, getFlowTarget(targetPct: 0.75, accountCapacity: 0.5, allocFlowMode: 0), accuracy: 0.001) + XCTAssertEqual(0.563, getFlowTarget(targetPct: 0.75, accountCapacity: 0.5, allocFlowMode: 0.5), accuracy: 0.001) + XCTAssertEqual(0.469, getFlowTarget(targetPct: 0.5, accountCapacity: 0.75, allocFlowMode: 0.75), accuracy: 0.001) + XCTAssertEqual(0.438, getFlowTarget(targetPct: 0.5, accountCapacity: 0.75, allocFlowMode: 0.5), accuracy: 0.001) + } + + func testSurplusRequired() { + XCTAssertEqual(0, getSurplusRequired(remainingAssetClassCapacity: 0, forwardAssetClassLimit: 0, flowTarget: 0)) + XCTAssertEqual(0, getSurplusRequired(remainingAssetClassCapacity: 0, forwardAssetClassLimit: 0, flowTarget: 1)) + XCTAssertEqual(0, getSurplusRequired(remainingAssetClassCapacity: 0, forwardAssetClassLimit: 1, flowTarget: 0)) + XCTAssertEqual(0, getSurplusRequired(remainingAssetClassCapacity: 0, forwardAssetClassLimit: 1, flowTarget: 1)) + XCTAssertEqual(1, getSurplusRequired(remainingAssetClassCapacity: 1, forwardAssetClassLimit: 0, flowTarget: 0)) + XCTAssertEqual(0, getSurplusRequired(remainingAssetClassCapacity: 1, forwardAssetClassLimit: 0, flowTarget: 1)) + XCTAssertEqual(0, getSurplusRequired(remainingAssetClassCapacity: 1, forwardAssetClassLimit: 1, flowTarget: 1)) + + XCTAssertEqual(0, getSurplusRequired(remainingAssetClassCapacity: 0, forwardAssetClassLimit: 0, flowTarget: 0.5)) + XCTAssertEqual(0, getSurplusRequired(remainingAssetClassCapacity: 0, forwardAssetClassLimit: 0.5, flowTarget: 0)) + XCTAssertEqual(0, getSurplusRequired(remainingAssetClassCapacity: 0, forwardAssetClassLimit: 0.5, flowTarget: 0.5)) + XCTAssertEqual(0.5, getSurplusRequired(remainingAssetClassCapacity: 0.5, forwardAssetClassLimit: 0, flowTarget: 0)) + XCTAssertEqual(0, getSurplusRequired(remainingAssetClassCapacity: 0.5, forwardAssetClassLimit: 0, flowTarget: 0.5)) + XCTAssertEqual(0, getSurplusRequired(remainingAssetClassCapacity: 0.5, forwardAssetClassLimit: 0.5, flowTarget: 0.5)) + + XCTAssertEqual(0, getSurplusRequired(remainingAssetClassCapacity: 0.75, forwardAssetClassLimit: 0.75, flowTarget: 0.75), accuracy: 0.001) + XCTAssertEqual(0, getSurplusRequired(remainingAssetClassCapacity: 0.75, forwardAssetClassLimit: 0.75, flowTarget: 0.5), accuracy: 0.001) + XCTAssertEqual(0.25, getSurplusRequired(remainingAssetClassCapacity: 0.75, forwardAssetClassLimit: 0.5, flowTarget: 0), accuracy: 0.001) + XCTAssertEqual(0, getSurplusRequired(remainingAssetClassCapacity: 0.75, forwardAssetClassLimit: 0.5, flowTarget: 0.5), accuracy: 0.001) + XCTAssertEqual(0, getSurplusRequired(remainingAssetClassCapacity: 0.5, forwardAssetClassLimit: 0.75, flowTarget: 0.75), accuracy: 0.001) + XCTAssertEqual(0, getSurplusRequired(remainingAssetClassCapacity: 0.5, forwardAssetClassLimit: 0.75, flowTarget: 0.5), accuracy: 0.001) + } + + func testGetUserMaxLimit() { + XCTAssertEqual(0, getUserMaxLimit(userLimit: 0, flowTarget: 0, accountCapacity: 0, surplusRequired: 0)) + XCTAssertEqual(0, getUserMaxLimit(userLimit: 0, flowTarget: 0, accountCapacity: 0, surplusRequired: 1)) + XCTAssertEqual(0, getUserMaxLimit(userLimit: 0, flowTarget: 0, accountCapacity: 1, surplusRequired: 0)) + XCTAssertEqual(1, getUserMaxLimit(userLimit: 0, flowTarget: 0, accountCapacity: 1, surplusRequired: 1)) + XCTAssertEqual(0, getUserMaxLimit(userLimit: 0, flowTarget: 1, accountCapacity: 0, surplusRequired: 0)) + XCTAssertEqual(0, getUserMaxLimit(userLimit: 0, flowTarget: 1, accountCapacity: 0, surplusRequired: 1)) + XCTAssertEqual(0, getUserMaxLimit(userLimit: 0, flowTarget: 1, accountCapacity: 1, surplusRequired: 0)) + XCTAssertEqual(1, getUserMaxLimit(userLimit: 0, flowTarget: 1, accountCapacity: 1, surplusRequired: 1)) + XCTAssertEqual(0, getUserMaxLimit(userLimit: 1, flowTarget: 0, accountCapacity: 0, surplusRequired: 0)) + XCTAssertEqual(0, getUserMaxLimit(userLimit: 1, flowTarget: 0, accountCapacity: 0, surplusRequired: 1)) + XCTAssertEqual(0, getUserMaxLimit(userLimit: 1, flowTarget: 0, accountCapacity: 1, surplusRequired: 0)) + XCTAssertEqual(1, getUserMaxLimit(userLimit: 1, flowTarget: 0, accountCapacity: 1, surplusRequired: 1)) + XCTAssertEqual(0, getUserMaxLimit(userLimit: 1, flowTarget: 1, accountCapacity: 0, surplusRequired: 0)) + XCTAssertEqual(0, getUserMaxLimit(userLimit: 1, flowTarget: 1, accountCapacity: 0, surplusRequired: 1)) + XCTAssertEqual(1, getUserMaxLimit(userLimit: 1, flowTarget: 1, accountCapacity: 1, surplusRequired: 0)) + XCTAssertEqual(1, getUserMaxLimit(userLimit: 1, flowTarget: 1, accountCapacity: 1, surplusRequired: 1)) + + XCTAssertEqual(0, getUserMaxLimit(userLimit: 0, flowTarget: 0, accountCapacity: 0, surplusRequired: 0)) + XCTAssertEqual(0, getUserMaxLimit(userLimit: 0, flowTarget: 0, accountCapacity: 0, surplusRequired: 0.5)) + XCTAssertEqual(0, getUserMaxLimit(userLimit: 0, flowTarget: 0, accountCapacity: 0.5, surplusRequired: 0)) + XCTAssertEqual(0.5, getUserMaxLimit(userLimit: 0, flowTarget: 0, accountCapacity: 0.5, surplusRequired: 0.5)) + XCTAssertEqual(0, getUserMaxLimit(userLimit: 0, flowTarget: 0.5, accountCapacity: 0, surplusRequired: 0)) + XCTAssertEqual(0, getUserMaxLimit(userLimit: 0, flowTarget: 0.5, accountCapacity: 0, surplusRequired: 0.5)) + XCTAssertEqual(0, getUserMaxLimit(userLimit: 0, flowTarget: 0.5, accountCapacity: 0.5, surplusRequired: 0)) + XCTAssertEqual(0.5, getUserMaxLimit(userLimit: 0, flowTarget: 0.5, accountCapacity: 0.5, surplusRequired: 0.5)) + XCTAssertEqual(0, getUserMaxLimit(userLimit: 0.5, flowTarget: 0, accountCapacity: 0, surplusRequired: 0)) + XCTAssertEqual(0, getUserMaxLimit(userLimit: 0.5, flowTarget: 0, accountCapacity: 0, surplusRequired: 0.5)) + XCTAssertEqual(0, getUserMaxLimit(userLimit: 0.5, flowTarget: 0, accountCapacity: 0.5, surplusRequired: 0)) + XCTAssertEqual(0.5, getUserMaxLimit(userLimit: 0.5, flowTarget: 0, accountCapacity: 0.5, surplusRequired: 0.5)) + XCTAssertEqual(0, getUserMaxLimit(userLimit: 0.5, flowTarget: 0.5, accountCapacity: 0, surplusRequired: 0)) + XCTAssertEqual(0, getUserMaxLimit(userLimit: 0.5, flowTarget: 0.5, accountCapacity: 0, surplusRequired: 0.5)) + XCTAssertEqual(0.5, getUserMaxLimit(userLimit: 0.5, flowTarget: 0.5, accountCapacity: 0.5, surplusRequired: 0)) + XCTAssertEqual(0.5, getUserMaxLimit(userLimit: 0.5, flowTarget: 0.5, accountCapacity: 0.5, surplusRequired: 0.5)) + + XCTAssertEqual(1, getUserMaxLimit(userLimit: 1, flowTarget: 1, accountCapacity: 1, surplusRequired: 1)) + XCTAssertEqual(1, getUserMaxLimit(userLimit: 1, flowTarget: 1, accountCapacity: 1, surplusRequired: 0.25)) + XCTAssertEqual(0.25, getUserMaxLimit(userLimit: 1, flowTarget: 1, accountCapacity: 0.25, surplusRequired: 1)) + XCTAssertEqual(0.25, getUserMaxLimit(userLimit: 1, flowTarget: 1, accountCapacity: 0.25, surplusRequired: 0.25)) + XCTAssertEqual(1, getUserMaxLimit(userLimit: 1, flowTarget: 0.25, accountCapacity: 1, surplusRequired: 1)) + XCTAssertEqual(0.5, getUserMaxLimit(userLimit: 1, flowTarget: 0.25, accountCapacity: 1, surplusRequired: 0.25)) + XCTAssertEqual(0.25, getUserMaxLimit(userLimit: 1, flowTarget: 0.25, accountCapacity: 0.25, surplusRequired: 1)) + XCTAssertEqual(0.25, getUserMaxLimit(userLimit: 1, flowTarget: 0.25, accountCapacity: 0.25, surplusRequired: 0.25)) + XCTAssertEqual(1, getUserMaxLimit(userLimit: 0.25, flowTarget: 1, accountCapacity: 1, surplusRequired: 1)) + XCTAssertEqual(0.5, getUserMaxLimit(userLimit: 0.25, flowTarget: 1, accountCapacity: 1, surplusRequired: 0.25)) + XCTAssertEqual(0.25, getUserMaxLimit(userLimit: 0.25, flowTarget: 1, accountCapacity: 0.25, surplusRequired: 1)) + XCTAssertEqual(0.25, getUserMaxLimit(userLimit: 0.25, flowTarget: 1, accountCapacity: 0.25, surplusRequired: 0.25)) + XCTAssertEqual(1, getUserMaxLimit(userLimit: 0.25, flowTarget: 0.25, accountCapacity: 1, surplusRequired: 1)) + XCTAssertEqual(0.5, getUserMaxLimit(userLimit: 0.25, flowTarget: 0.25, accountCapacity: 1, surplusRequired: 0.25)) + XCTAssertEqual(0.25, getUserMaxLimit(userLimit: 0.25, flowTarget: 0.25, accountCapacity: 0.25, surplusRequired: 1)) + XCTAssertEqual(0.25, getUserMaxLimit(userLimit: 0.25, flowTarget: 0.25, accountCapacity: 0.25, surplusRequired: 0.25)) + } + + func testHalfCapacityFlow() { + let flowTarget = getFlowTarget(targetPct: 1, + accountCapacity: 0.5, + allocFlowMode: 1) + let surplusRequired = getSurplusRequired(remainingAssetClassCapacity: 1, + forwardAssetClassLimit: 0, + flowTarget: flowTarget) + let limit = getUserMaxLimit(userLimit: 0.5, + flowTarget: flowTarget, + accountCapacity: 0.5, + surplusRequired: surplusRequired) + XCTAssertEqual(limit, 0.5) + } + + func testHalfCapacityMirror() { + let flowTarget = getFlowTarget(targetPct: 1, + accountCapacity: 0.5, + allocFlowMode: 0) + let surplusRequired = getSurplusRequired(remainingAssetClassCapacity: 1, + forwardAssetClassLimit: 0, + flowTarget: flowTarget) + let limit = getUserMaxLimit(userLimit: 1, + flowTarget: flowTarget, + accountCapacity: 0.5, + surplusRequired: surplusRequired) + XCTAssertEqual(limit, 0.5) + } + + func testHalfMirrorHalfTarget() { + let flowTarget = getFlowTarget(targetPct: 0.5, + accountCapacity: 1, + allocFlowMode: 0.5) + let surplusRequired = getSurplusRequired(remainingAssetClassCapacity: 1, + forwardAssetClassLimit: 0, + flowTarget: flowTarget) + let limit = getUserMaxLimit(userLimit: 1, + flowTarget: flowTarget, + accountCapacity: 1, + surplusRequired: surplusRequired) + XCTAssertEqual(limit, 1.0) + } + + func testFullMirrorHalfTarget() { + let flowTarget = getFlowTarget(targetPct: 0.5, + accountCapacity: 1, + allocFlowMode: 0) + let surplusRequired = getSurplusRequired(remainingAssetClassCapacity: 1, + forwardAssetClassLimit: 0, + flowTarget: flowTarget) + let limit = getUserMaxLimit(userLimit: 1, + flowTarget: flowTarget, + accountCapacity: 1, + surplusRequired: surplusRequired) + XCTAssertEqual(limit, 1.0) + } + + func testFullMirrorHalfTargetQuarterCapacity() { + let flowTarget = getFlowTarget(targetPct: 0.5, + accountCapacity: 0.25, + allocFlowMode: 0) + let surplusRequired = getSurplusRequired(remainingAssetClassCapacity: 1, + forwardAssetClassLimit: 0, + flowTarget: flowTarget) + let limit = getUserMaxLimit(userLimit: 1, + flowTarget: flowTarget, + accountCapacity: 0.25, + surplusRequired: surplusRequired) + XCTAssertEqual(limit, 0.25) + } + + func testHalfMirrorQuarterTarget() { + let flowTarget = getFlowTarget(targetPct: 0.25, + accountCapacity: 1, + allocFlowMode: 0.5) + let surplusRequired = getSurplusRequired(remainingAssetClassCapacity: 1, + forwardAssetClassLimit: 0, + flowTarget: flowTarget) + let limit = getUserMaxLimit(userLimit: 1, + flowTarget: flowTarget, + accountCapacity: 1, + surplusRequired: surplusRequired) + XCTAssertEqual(limit, 1.0) + } + + func testForwardLimitIgnored() { + let flowTarget = getFlowTarget(targetPct: 0.25, + accountCapacity: 1, + allocFlowMode: 0.5) + let surplusRequired = getSurplusRequired(remainingAssetClassCapacity: 1, + forwardAssetClassLimit: 0.20, + flowTarget: flowTarget) + let limit = getUserMaxLimit(userLimit: 1, + flowTarget: flowTarget, + accountCapacity: 1, + surplusRequired: surplusRequired) + XCTAssertEqual(limit, 0.8) + } + + func testForwardLimit() { + let flowTarget = getFlowTarget(targetPct: 0.15, + accountCapacity: 1, + allocFlowMode: 0) + let surplusRequired = getSurplusRequired(remainingAssetClassCapacity: 1, + forwardAssetClassLimit: 0.20, + flowTarget: flowTarget) + let limit = getUserMaxLimit(userLimit: 1, + flowTarget: flowTarget, + accountCapacity: 1, + surplusRequired: surplusRequired) + XCTAssertEqual(limit, 0.8) + } +} diff --git a/Tests/Allocate/GetCapacitiesMapTests.swift b/Tests/Allocate/GetCapacitiesMapTests.swift new file mode 100644 index 0000000..89294a4 --- /dev/null +++ b/Tests/Allocate/GetCapacitiesMapTests.swift @@ -0,0 +1,67 @@ +// +// GetCapacitiesMapTests.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import XCTest + +import FlowBase +import AllocData + +@testable import FlowAllocLow + +class GetCapacitiesMapTests: XCTestCase { + var model: BaseModel! + var accountPresentValueMap: AccountPresentValueMap! + + override func setUp() { + let equities = MAsset(assetID: "LC", title: "Equities") + let bonds = MAsset(assetID: "Bond", title: "Bonds") + let account1 = MAccount(accountID: "1", title: "My First") + let holding1a = MHolding(accountID: "1", securityID: "SPY", lotID: "", shareCount: 8, shareBasis: 1) + let holding1b = MHolding(accountID: "1", securityID: "AGG", lotID: "", shareCount: 2, shareBasis: 1) + let account2 = MAccount(accountID: "2", title: "My Second") + let holding2a = MHolding(accountID: "2", securityID: "SPY", lotID: "", shareCount: 2, shareBasis: 1) + let holding2b = MHolding(accountID: "2", securityID: "AGG", lotID: "", shareCount: 8, shareBasis: 1) + let security1 = MSecurity(securityID: "BND", sharePrice: 1) + let security2 = MSecurity(securityID: "AGG", sharePrice: 1) + let security3 = MSecurity(securityID: "SPY", sharePrice: 2) + let security4 = MSecurity(securityID: "VOO", sharePrice: 1) + let accounts = [account1, account2] + model = BaseModel(accounts: accounts, + assets: [equities, bonds], + securities: [security1, security2, security3, security4], + holdings: [holding1a, holding1b, holding2a, holding2b]) + } + + func refreshMaps() { + accountPresentValueMap = MAccount.getAccountPresentValueMap(model.accounts.map(\.primaryKey), + model.makeAccountHoldingsMap(), + model.makeSecurityMap()) + } + + func testNoValue() throws { + let account0 = MAccount(accountID: "1", title: "My First") + let model0 = BaseModel(accounts: [account0]) + let map0 = MAccount.getAccountPresentValueMap(model0.accounts.map(\.primaryKey), + model0.makeAccountHoldingsMap(), + model0.makeSecurityMap()) + let expected = AccountCapacitiesMap() + let actual = getCapacitiesMap(model0.accounts.map(\.primaryKey), map0) + XCTAssertEqual(expected, actual) + } + + func testTwoAccountsWithFourHoldings() throws { + refreshMaps() + let account1 = MAccount.Key(accountID: "1") + let account2 = MAccount.Key(accountID: "2") + let actual = getCapacitiesMap(model.accounts.map(\.primaryKey), accountPresentValueMap) + let expected = [account1: 0.6, account2: 0.4] + XCTAssertEqual(expected, actual) + } +} diff --git a/Tests/Allocate/GetLimitPctMapTests.swift b/Tests/Allocate/GetLimitPctMapTests.swift new file mode 100644 index 0000000..f53317b --- /dev/null +++ b/Tests/Allocate/GetLimitPctMapTests.swift @@ -0,0 +1,62 @@ +// +// GetLimitPctMapTests.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import XCTest + +import FlowBase +import AllocData + +@testable import FlowAllocLow + +class GetLimitPctMapTests: XCTestCase { + + let account1 = MAccount.Key(accountID: "1") + let account2 = MAccount.Key(accountID: "2") + let bond = MAsset.Key(assetID: "Bond") + let lc = MAsset.Key(assetID: "LC") + let gold = MAsset.Key(assetID: "Gold") + + func testNoCaps() throws { + let actual = getLimitPctMap([]) + let expected = LimitPctMap() + XCTAssertEqual(expected, actual) + } + + func testOneSlice() throws { + let slice = MCap(accountID: "1", assetID: "LC", limitPct: 0.14) + let capMap = [account1: [slice]] + let actual = getLimitPctMap(capMap[account1] ?? []) + let expected = [MAsset.Key(assetID: "LC"): 0.14] + XCTAssertEqual(expected, actual) + } + + // not ideal, but import logic should be preventing this + func testUseLastIfDuplicatesWithinAccount() throws { + let slice1 = MCap(accountID: "1", assetID: "LC", limitPct: 0.14) + let slice2 = MCap(accountID: "1", assetID: "LC", limitPct: 0.10) + let capMap = [account1: [slice1, slice2]] + let actual = getLimitPctMap(capMap[account1] ?? []) + let expected = [MAsset.Key(assetID: "LC"): 0.10] + XCTAssertEqual(expected, actual) + } + + func testThreeSlicesOverTwoAccounts() throws { + let slice1 = MCap(accountID: "1", assetID: "LC", limitPct: 0.14) + let slice2 = MCap(accountID: "1", assetID: "Bond", limitPct: 0.10) + let slice3 = MCap(accountID: "2", assetID: "Gold", limitPct: 0.15) + let capMap = [account1: [slice1, slice2], account2: [slice3]] + let actual1 = getLimitPctMap(capMap[account1] ?? []) + let expected1 = [lc: 0.14, bond: 0.10] + XCTAssertEqual(expected1, actual1) + let actual2 = getLimitPctMap(capMap[account2] ?? []) + let expected2 = [gold: 0.15] + XCTAssertEqual(expected2, actual2) + } +} diff --git a/Tests/Allocate/GetVertLimitsTests.swift b/Tests/Allocate/GetVertLimitsTests.swift new file mode 100644 index 0000000..85eb634 --- /dev/null +++ b/Tests/Allocate/GetVertLimitsTests.swift @@ -0,0 +1,124 @@ +// +// GetVertLimitsTests.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import XCTest + +import FlowBase +import AllocData + +@testable import FlowAllocLow + +class GetVertLimitsTests: XCTestCase { + let modelJSON = """ + { + "id": "97A51E12-BEA0-4A70-BC8C-B93F39213025", + "updatedAt": 639202449, + "assets": [ + { "title": "LC", "assetID": "LC", "colorCode": 0 }, + { "title": "Bond", "assetID": "Bond", "colorCode": 0 }, + { "title": "Cash", "assetID": "Cash", "colorCode": 0 } + ], + "accounts": [ + { + "accountID": "1", + "title": "Taxable", + "isTaxable": false, + "accountStrategyID": "1" + }, + { "accountID": "2", + "title": "Roth", + "isTaxable": false, + "accountStrategyID": "1" + } + ], + "securities": [ + { "securityAssetID": "Cash", "securityID": "Cash", "sharePrice": 1 }, + { "securityAssetID": "LC", "securityID": "SPY", "sharePrice": 1 }, + { "securityAssetID": "Bond", "securityID": "AGG", "sharePrice": 1 } + ], + "holdings": [ + { + "holdingAccountID": "1", + "shareCount": 100, + "sharePrice": 1, + "holdingSecurityID": "Cash", + "shareBasis": 1 + }, + { + "holdingAccountID": "2", + "shareCount": 100, + "sharePrice": 1, + "holdingSecurityID": "Cash", + "shareBasis": 1 + } + ], + "strategies": [ + { + "strategyID": "1", + "title": "60/40" + }, + ], + "allocations": [ + { "allocationStrategyID": "1", "allocationAssetID": "LC", "targetPct": 0.60 }, + { "allocationStrategyID": "1", "allocationAssetID": "Bond", "targetPct": 0.40 } + ], + "trackers": [], + "caps": [], + "transactions": [], + "valuationSnapshots": [], + "valuationAccounts": [], + "valuationCashflows": [], + "valuationPositions": [] + } + """ + var model: BaseModel! + + let lc = MAsset.Key(assetID: "LC") + let bond = MAsset.Key(assetID: "Bond") + let strategy1 = MStrategy.Key(strategyID: "1") + let account1 = MAccount.Key(accountID: "1") + let account2 = MAccount.Key(accountID: "2") + + override func setUpWithError() throws { + model = try StorageManager.decode(fromJSON: modelJSON) + } + + func testBondLimit() throws { + for (limitPct, expected) in [ + 0.0: [account1: [lc: 0.50, bond: 0.00], account2: [lc: 0.3, bond: 0.2]], + 0.1: [account1: [lc: 0.45, bond: 0.05], account2: [lc: 0.3, bond: 0.2]], + 0.2: [account1: [lc: 0.40, bond: 0.10], account2: [lc: 0.3, bond: 0.2]], + 0.3: [account1: [lc: 0.35, bond: 0.15], account2: [lc: 0.3, bond: 0.2]], + 0.4: [account1: [lc: 0.30, bond: 0.20], account2: [lc: 0.3, bond: 0.2]], + 0.5: [account1: [lc: 0.30, bond: 0.20], account2: [lc: 0.3, bond: 0.2]], + ] { + let cap1 = MCap(accountID: "1", assetID: "Bond", limitPct: limitPct) + model.caps = [cap1] + // model.settings.strategyID = "1" + let ax = LowContext(model, strategyKey: strategy1) + let actual = ax.accountUserVertLimitMap + XCTAssertEqual(expected, actual, "for limitPct=\(limitPct)") + } + } + + func testGetUserVertLimits() throws { + let allocs = [ + AssetValue(lc, 0.6), + AssetValue(bond, 0.4), + ] + let allocMap = AssetValue.getAssetValueMap(from: allocs) + let limitPctMap = [bond: 0.0] + let expected = [lc: 0.5, bond: 0.0] + let actual = try getUserVertLimits(allocMap: allocMap, + limitPctMap: limitPctMap, + accountCapacity: 0.5) + XCTAssertEqual(expected, actual) + } +} diff --git a/Tests/Core/BaseParamsTests.swift b/Tests/Core/BaseParamsTests.swift new file mode 100644 index 0000000..22ceac9 --- /dev/null +++ b/Tests/Core/BaseParamsTests.swift @@ -0,0 +1,38 @@ +// +// BaseParamsTests.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import XCTest + +import FlowBase +import AllocData + +@testable import FlowAllocLow + +class BaseParamsTests: XCTestCase { + + let account1 = MAccount.Key(accountID: "1") + let bond = MAsset.Key(assetID: "Bond") + + func testValidateFailsDueToMissingAccounts() throws { + XCTAssertThrowsError(try BaseParams().validate()) { error in + XCTAssertEqual(error as! AllocLowError2, AllocLowError2.invalidParams("missing accounts")) + } + } + + func testValidateMissingAllocation() throws { + XCTAssertThrowsError(try BaseParams(accountKeys: [account1]).validate()) { error in + XCTAssertEqual(error as! AllocLowError2, AllocLowError2.invalidParams("missing allocation")) + } + } + + func testValidateSucceeds() throws { + XCTAssertNoThrow(try BaseParams(accountKeys: [account1], assetKeys: [bond]).validate()) + } +} diff --git a/Tests/Model/MHoldingTests.swift b/Tests/Model/MHoldingTests.swift new file mode 100644 index 0000000..26771ff --- /dev/null +++ b/Tests/Model/MHoldingTests.swift @@ -0,0 +1,65 @@ +// +// MHoldingTests.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import XCTest + +import FlowBase +import AllocData + +@testable import FlowAllocLow + +class MHoldingTests2: XCTestCase { + + func testAssetClasses() throws { + let equities = "Equities" + let bonds = "Bonds" + let spy = MSecurity(securityID: "SPY", assetID: equities) + let voo = MSecurity(securityID: "VOO", assetID: equities) + let bnd = MSecurity(securityID: "BND", assetID: bonds) + let securityMap: SecurityMap = MSecurity.makeAllocMap([spy, voo, bnd]) + let holding1 = MHolding(accountID: "1", securityID: "SPY", lotID: "", shareCount: 1, shareBasis: 1) + let holding2 = MHolding(accountID: "1", securityID: "VOO", lotID: "", shareCount: 1, shareBasis: 1) + let holding3 = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 1, shareBasis: 1) + let expected = [MAsset.normalizeID(bonds), MAsset.normalizeID(equities)] + let actual = MHolding.getAssetKeys([holding1, holding2, holding3], securityMap: securityMap).map(\.assetNormID) + XCTAssertEqual(expected, actual) + } + + + func testAnyShareCountAllowed() throws { + for shareCount in [-100, -0.01, 0, 0.01, 100] { + let holding = MHolding(accountID: "1", securityID: "SPY", lotID: "", shareCount: shareCount, shareBasis: 1) // , sharePrice: 1 + XCTAssertNoThrow(try holding.validate()) + } + } + + func testPresentValue() throws { + let securityMap = [MSecurity.Key(securityID: "SPY"): MSecurity(securityID: "SPY", assetID: "X", sharePrice: 7)] + let holding = MHolding(accountID: "1", securityID: "SPY", lotID: "", shareCount: 13, shareBasis: 200) // , sharePrice: 7 + let expected = 13.0 * 7.0 + let actual = holding.getPresentValue(securityMap) + XCTAssertEqual(expected, actual) + } + + func testCostBasis() throws { + let holding = MHolding(accountID: "1", securityID: "SPY", lotID: "", shareCount: 7, shareBasis: 200) // , sharePrice: 1 + let expected = 7.0 * 200 + let actual = holding.costBasis + XCTAssertEqual(expected, actual) + } + + func testGainLoss() throws { + let securityMap = [MSecurity.Key(securityID: "SPY"): MSecurity(securityID: "SPY", assetID: "X", sharePrice: 13)] + let holding = MHolding(accountID: "1", securityID: "SPY", lotID: "", shareCount: 7, shareBasis: 200) // , sharePrice: 13 + let expected = 7.0 * (13 - 200) + let actual = holding.getGainLoss(securityMap) + XCTAssertEqual(expected, actual) + } +} diff --git a/Tests/Rebalance/BaseSaleTests.swift b/Tests/Rebalance/BaseSaleTests.swift new file mode 100644 index 0000000..6a65366 --- /dev/null +++ b/Tests/Rebalance/BaseSaleTests.swift @@ -0,0 +1,111 @@ +// +// BaseSaleTests.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import XCTest + +import FlowBase +import AllocData + +@testable import FlowAllocLow + +class BaseSaleTests: XCTestCase { + var securityMap: SecurityMap! + + let account1 = MAccount.Key(accountID: "1") + let account2 = MAccount.Key(accountID: "2") + let bond = MAsset.Key(assetID: "Bond") + let equities = MAsset.Key(assetID: "Equities") + let bnd = MSecurity.Key(securityID: "BND") + + override func setUp() { + securityMap = MSecurity.makeAllocMap([MSecurity(securityID: "BND", sharePrice: 1), + MSecurity(securityID: "AGG", sharePrice: 1)]) + } + + func testNoHoldings() throws { + let so = Sale(assetKey: MAsset.Key(assetID: "Bond"), targetAmount: 100) + XCTAssertEqual(0, so.proceeds) + XCTAssertEqual(0, so.netGainLoss) + XCTAssertEqual(0, so.absoluteGains) + } + + func testOneHoldingWithGain() throws { + let h = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 2, shareBasis: 0.50) + let pv = h.getPresentValue(securityMap)! + let lh = LiquidateHolding(h, presentValue: pv) + let so = Sale(assetKey: MAsset.Key(assetID: "Bond"), targetAmount: 100, liquidateHoldings: [lh]) + XCTAssertEqual(2, so.proceeds) + XCTAssertEqual(1, so.netGainLoss) + XCTAssertEqual(1, so.absoluteGains) + } + + func testOneHoldingWithLoss() throws { + let h = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 2, shareBasis: 1.50) + let pv = h.getPresentValue(securityMap)! + let lh = LiquidateHolding(h, presentValue: pv) + let so = Sale(assetKey: MAsset.Key(assetID: "Bond"), targetAmount: 100, liquidateHoldings: [lh]) + XCTAssertEqual(2, so.proceeds) + XCTAssertEqual(-1, so.netGainLoss) + XCTAssertEqual(0, so.absoluteGains) + } + + func testOneHoldingWithNilShareBasis() throws { + let h = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 2, shareBasis: nil) + let pv = h.getPresentValue(securityMap)! + let lh = LiquidateHolding(h, presentValue: pv) + let so = Sale(assetKey: MAsset.Key(assetID: "Bond"), targetAmount: 100, liquidateHoldings: [lh]) + XCTAssertEqual(2, so.proceeds) + XCTAssertEqual(0, so.netGainLoss) + XCTAssertEqual(0, so.absoluteGains) + } + + func testOneHoldingWithGainAndFractionalSale() throws { + let h = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 2, shareBasis: 0.50) + let pv = h.getPresentValue(securityMap)! + let lh = LiquidateHolding(h, presentValue: pv, fraction: 0.5) // sell half of position + XCTAssertEqual(2.0, lh.presentValue) + XCTAssertEqual(0.5, lh.fraction) + XCTAssertEqual(0.5, lh.fractionalGainLoss) + XCTAssertEqual(1.0, lh.fractionalShareCount) + XCTAssertEqual(1.0, lh.fractionalValue) + let so = Sale(assetKey: MAsset.Key(assetID: "Bond"), targetAmount: 100, liquidateHoldings: [lh]) + XCTAssertEqual(1, so.proceeds) + XCTAssertEqual(0.5, so.netGainLoss) + XCTAssertEqual(0.5, so.absoluteGains) + } + + func testOneHoldingWithLossAndFractionalSale() throws { + let h = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 2, shareBasis: 1.50) + let pv = h.getPresentValue(securityMap)! + let lh = LiquidateHolding(h, presentValue: pv, fraction: 0.5) // sell half of position + XCTAssertEqual(2.0, lh.presentValue) + XCTAssertEqual(0.5, lh.fraction) + XCTAssertEqual(-0.5, lh.fractionalGainLoss) + XCTAssertEqual(1.0, lh.fractionalShareCount) + XCTAssertEqual(1.0, lh.fractionalValue) + let so = Sale(assetKey: MAsset.Key(assetID: "Bond"), targetAmount: 100, liquidateHoldings: [lh]) + XCTAssertEqual(1, so.proceeds) + XCTAssertEqual(-0.5, so.netGainLoss) + XCTAssertEqual(0, so.absoluteGains) + } + + func testTwoHoldingsWithGainAndLoss() throws { + let h1 = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 2, shareBasis: 1.50) // loss 1.0 + let h2 = MHolding(accountID: "1", securityID: "AGG", lotID: "", shareCount: 2, shareBasis: 0.75) // gain 0.5 + let pv1 = h1.getPresentValue(securityMap)! + let pv2 = h2.getPresentValue(securityMap)! + let lh1 = LiquidateHolding(h1, presentValue: pv1) + let lh2 = LiquidateHolding(h2, presentValue: pv2) + let so = Sale(assetKey: MAsset.Key(assetID: "Bond"), targetAmount: 100, liquidateHoldings: [lh1, lh2]) + XCTAssertEqual(4, so.proceeds) + XCTAssertEqual(-0.5, so.netGainLoss) + XCTAssertEqual(0.5, so.absoluteGains) + } +} diff --git a/Tests/Rebalance/GetHoldingsSummaryMapTests.swift b/Tests/Rebalance/GetHoldingsSummaryMapTests.swift new file mode 100644 index 0000000..ca80d40 --- /dev/null +++ b/Tests/Rebalance/GetHoldingsSummaryMapTests.swift @@ -0,0 +1,83 @@ +// +// GetHoldingsSummaryMapTests.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import XCTest + +import FlowBase +import AllocData +import FlowXCT + +@testable import FlowAllocLow + +class GetHoldingsSummaryMapTests: XCTestCase { + let asset1 = MAsset(assetID: "LC", title: "Large Cap") + let asset2 = MAsset(assetID: "Bond", title: "Bond", colorCode: 1) + let asset3 = MAsset(assetID: "CorpBond", title: "Corporate Bond", colorCode: 2) + var assets: [MAsset]! + + let security1 = MSecurity(securityID: "SPY", assetID: "LC", sharePrice: 100) + let security2 = MSecurity(securityID: "AGG", assetID: "Bond", sharePrice: 100) + let security3 = MSecurity(securityID: "CORP", assetID: "CorpBond", sharePrice: 100) + // deliberately no AMZN security + var securities: [MSecurity]! + + let account1 = MAccount(accountID: "1", title: "IRA", isTaxable: false) + let account2 = MAccount(accountID: "2", title: "Taxable", isTaxable: true) + let account3 = MAccount(accountID: "3", title: "Concentrated", isTaxable: true) + var accounts: [MAccount]! + + let holding1a = MHolding(accountID: "1", securityID: "SPY", lotID: "", shareCount: 12, shareBasis: 110) + let holding1b = MHolding(accountID: "1", securityID: "AGG", lotID: "", shareCount: 10, shareBasis: 80) + let holding1c = MHolding(accountID: "1", securityID: "SPY", lotID: "1", shareCount: 5, shareBasis: 70) + let holding2 = MHolding(accountID: "2", securityID: "CORP", lotID: "", shareCount: 13, shareBasis: 70) + let holding3a = MHolding(accountID: "3", securityID: "AMZN", lotID: "", shareCount: 1, shareBasis: 1500) // sharePrice: 2000 + let holding3b = MHolding(accountID: "3", securityID: "AGG", lotID: "66", shareCount: 8, shareBasis: 70) + + let bond = MAsset.Key(assetID: "Bond") + let lc = MAsset.Key(assetID: "LC") + let corpbond = MAsset.Key(assetID: "CorpBond") + + let agg = MSecurity.Key(securityID: "AGG") + let spy = MSecurity.Key(securityID: "SPY") + let corp = MSecurity.Key(securityID: "CORP") + + var holdings: [MHolding]! + var model: BaseModel! + var accountHoldingsMap: AccountHoldingsMap! + + override func setUp() { + assets = [asset1, asset2, asset3] + securities = [security1, security2, security3] + accounts = [account1, account2, account3] + holdings = [holding1a, holding1b, holding1c, holding2, holding3a, holding3b] + model = BaseModel(accounts: accounts, assets: assets, securities: securities, holdings: holdings) + } + + func testHoldingsSummary() throws { + let expected: AssetHoldingsSummaryMap = [lc: HoldingsSummary(presentValue: (12 + 5) * 100, costBasis: 12 * 110 + 5 * 70, count: 2, tickerShareMap: [spy: 17]), + bond: HoldingsSummary(presentValue: 10 * 100, costBasis: 10 * 80, count: 1, tickerShareMap: [agg: 10])] + let actual = HoldingsSummary.getAssetSummaryMap(account1.primaryKey, model.makeAccountHoldingsMap(), model.makeSecurityMap()) + XCTAssertEqual(expected, actual) + } + + func testAccountHoldingsSummaryMap() throws { + let accountKey1 = account1.primaryKey + let accountKey2 = account2.primaryKey + let accountKey3 = account3.primaryKey + + + let expected: AccountAssetHoldingsSummaryMap = [accountKey1: [lc: HoldingsSummary(presentValue: (12 + 5) * 100, costBasis: 12 * 110 + 5 * 70, count: 2, tickerShareMap: [spy: 17]), + bond: HoldingsSummary(presentValue: 10 * 100, costBasis: 10 * 80, count: 1, tickerShareMap: [agg: 10])], + accountKey2: [corpbond: HoldingsSummary(presentValue: 1300, costBasis: 910, count: 1, tickerShareMap: [corp: 13])], + accountKey3: [bond: HoldingsSummary(presentValue: 8 * 100, costBasis: 8 * 70, count: 1, tickerShareMap: [agg: 8])]] + let actual = HoldingsSummary.getAccountAssetSummaryMap(accounts.map(\.primaryKey), model.makeAccountHoldingsMap(), model.makeSecurityMap()) + XCTAssertEqual(expected, actual) + } +} diff --git a/Tests/Rebalance/GetLiquidateHoldingsTests.swift b/Tests/Rebalance/GetLiquidateHoldingsTests.swift new file mode 100644 index 0000000..ff3b4e8 --- /dev/null +++ b/Tests/Rebalance/GetLiquidateHoldingsTests.swift @@ -0,0 +1,168 @@ +// +// GetLiquidateHoldingsTests.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import XCTest + +import FlowBase +import AllocData + +@testable import FlowAllocLow + +class GetLiquidateHoldingsTests: XCTestCase { + var securityMap: SecurityMap! + + let account1 = MAccount.Key(accountID: "1") + let account2 = MAccount.Key(accountID: "2") + let bond = MAsset.Key(assetID: "Bond") + let equities = MAsset.Key(assetID: "Equities") + let bnd = MSecurity.Key(securityID: "BND") + + override func setUp() { + securityMap = MSecurity.makeAllocMap([MSecurity(securityID: "BND", sharePrice: 1), + MSecurity(securityID: "AGG", sharePrice: 1)]) + } + + func testNoHoldings() throws { + let sm = [bnd: MSecurity(securityID: "BND", assetID: "Bond", sharePrice: 1)] + var remainingToSell = 1.0 + let actual = LiquidateHolding.getLiquidations(sm, [], &remainingToSell) + XCTAssertEqual([], actual) + XCTAssertEqual(1.0, remainingToSell) + } + + func testOneHoldingWithRemainder() throws { + let sm = [bnd: MSecurity(securityID: "BND", assetID: "Bond", sharePrice: 1)] + let h1 = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 1) + var remainingToSell = 2.0 + let actual = LiquidateHolding.getLiquidations(sm, [h1], &remainingToSell) + let pv = h1.getPresentValue(securityMap)! + let expected = [LiquidateHolding(h1, presentValue: pv, fraction: 1.0)] + XCTAssertEqual(expected, actual) + XCTAssertEqual(1.0, remainingToSell) + } + + func testOneHoldingComplete() throws { + let sm = [bnd: MSecurity(securityID: "BND", assetID: "Bond", sharePrice: 1)] + let h1 = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 2) + var remainingToSell = 2.0 + let actual = LiquidateHolding.getLiquidations(sm, [h1], &remainingToSell) + let pv = h1.getPresentValue(securityMap)! + let expected = [LiquidateHolding(h1, presentValue: pv, fraction: 1.0)] + XCTAssertEqual(expected, actual) + XCTAssertEqual(0.0, remainingToSell) + } + + func testOneHoldingWithFractionalLiquidation() throws { + let sm = [bnd: MSecurity(securityID: "BND", assetID: "Bond", sharePrice: 1)] + let h1 = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 2) + var remainingToSell = 1.0 + let actual = LiquidateHolding.getLiquidations(sm, [h1], &remainingToSell) + let pv = h1.getPresentValue(securityMap)! + let expected = [LiquidateHolding(h1, presentValue: pv, fraction: 0.5)] + XCTAssertEqual(expected, actual) + XCTAssertEqual(0.0, remainingToSell) + } + + func testTwoHoldingsWithRemainder() throws { + let sm = [bnd: MSecurity(securityID: "BND", assetID: "Bond", sharePrice: 1), + MSecurity.Key(securityID: "AGG"): MSecurity(securityID: "AGG", assetID: "Bond", sharePrice: 1)] + let h1 = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 1) + let h2 = MHolding(accountID: "1", securityID: "AGG", lotID: "", shareCount: 2) + let holdings = [h1, h2] + var remainingToSell = 4.0 + let actual = LiquidateHolding.getLiquidations(sm, holdings, &remainingToSell) + let pv1 = h1.getPresentValue(securityMap)! + let pv2 = h2.getPresentValue(securityMap)! + let expected = [LiquidateHolding(h1, presentValue: pv1, fraction: 1.0), + LiquidateHolding(h2, presentValue: pv2, fraction: 1.0)] + XCTAssertEqual(expected, actual) + XCTAssertEqual(1.0, remainingToSell) + } + + func testTwoHoldingsComplete() throws { + let sm = MSecurity.makeAllocMap([ + MSecurity(securityID: "BND", assetID: "Bond", sharePrice: 1), + MSecurity(securityID: "AGG", assetID: "Bond", sharePrice: 1)]) + let h1 = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 1) + let h2 = MHolding(accountID: "1", securityID: "AGG", lotID: "", shareCount: 2) + let holdings = [h1, h2] + var remainingToSell = 3.0 + let actual = LiquidateHolding.getLiquidations(sm, holdings, &remainingToSell) + let pv1 = h1.getPresentValue(securityMap)! + let pv2 = h2.getPresentValue(securityMap)! + let expected = [LiquidateHolding(h1, presentValue: pv1, fraction: 1.0), + LiquidateHolding(h2, presentValue: pv2, fraction: 1.0)] + XCTAssertEqual(expected, actual) + XCTAssertEqual(0.0, remainingToSell) + } + + func testTwoHoldingsPartial() throws { + let sm = MSecurity.makeAllocMap([ + MSecurity(securityID: "BND", assetID: "Bond", sharePrice: 1), + MSecurity(securityID: "AGG", assetID: "Bond", sharePrice: 1)]) + let h1 = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 1) + let h2 = MHolding(accountID: "1", securityID: "AGG", lotID: "", shareCount: 2) + let holdings = [h1, h2] + var remainingToSell = 2.0 + let actual = LiquidateHolding.getLiquidations(sm, holdings, &remainingToSell) + let pv1 = h1.getPresentValue(securityMap)! + let pv2 = h2.getPresentValue(securityMap)! + let expected = [LiquidateHolding(h1, presentValue: pv1, fraction: 1.0), + LiquidateHolding(h2, presentValue: pv2, fraction: 0.5)] + XCTAssertEqual(expected, actual) + XCTAssertEqual(0.0, remainingToSell) + } + + func testOneHoldingSellingOrphan() throws { + let minimumAmount = 0.10 // include remainder if <= minimumAmount + let sm = MSecurity.makeAllocMap([ + MSecurity(securityID: "BND", assetID: "Bond", sharePrice: 1)]) + let h1 = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 1.10) + var remainingToSell = 1.0 + let actual = LiquidateHolding.getLiquidations(sm, [h1], &remainingToSell, minimumAmount) + let pv1 = h1.getPresentValue(securityMap)! + let expected = [LiquidateHolding(h1, presentValue: pv1, fraction: 1.0)] + XCTAssertEqual(expected, actual) + XCTAssertEqual(0.0, remainingToSell) + } + + func testOneHoldingNotSellingEntireHolding() throws { + let minimumAmount = 0.10 // we'll exceed this + let sm = MSecurity.makeAllocMap([ + MSecurity(securityID: "BND", assetID: "Bond", sharePrice: 1)]) + let h1 = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 1.11) + var remainingToSell = 1.0 + let actual = LiquidateHolding.getLiquidations(sm, [h1], &remainingToSell, minimumAmount) + XCTAssertEqual(0.0, remainingToSell) + XCTAssertEqual(actual[0].fraction, 0.901, accuracy: 0.001) + } + + func testTwoHoldingsLiquidateWithSmallerGainLoss() throws { + let securityMap = MSecurity.makeAllocMap([ + MSecurity(securityID: "BND", assetID: "Bond", sharePrice: 1), + MSecurity(securityID: "AGG", assetID: "Bond", sharePrice: 1)]) + let h1 = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 1, shareBasis: 1.0) // flat + let h2 = MHolding(accountID: "1", securityID: "AGG", lotID: "", shareCount: 2, shareBasis: 1.1) // smaller gainLoss + let holdingsUnsorted = [h1, h2] + var remainingToSell = 2.5 + + // the sort is done in getAssetHoldingsMap, not in getLiquidations + let ahMap = MHolding.getAssetHoldingsMap(holdingsUnsorted, securityMap) + let holdingsSorted = ahMap[bond]! + + let actual = LiquidateHolding.getLiquidations(securityMap, holdingsSorted, &remainingToSell) + let pv1 = h1.getPresentValue(securityMap)! + let pv2 = h2.getPresentValue(securityMap)! + let expected = [LiquidateHolding(h2, presentValue: pv1, fraction: 1.0), + LiquidateHolding(h1, presentValue: pv2, fraction: 0.5)] + XCTAssertEqual(expected, actual) + XCTAssertEqual(0.0, remainingToSell) + } +} diff --git a/Tests/Rebalance/GetPurchasesTests.swift b/Tests/Rebalance/GetPurchasesTests.swift new file mode 100644 index 0000000..15b8e71 --- /dev/null +++ b/Tests/Rebalance/GetPurchasesTests.swift @@ -0,0 +1,81 @@ +// +// BasePurchaseTests.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import XCTest + +import FlowBase +import AllocData + +@testable import FlowAllocLow + +class GetPurchasesTests: XCTestCase { + let cashAssetKey = MAsset.Key(assetID: "Cash") + let cashAssetKeySet = Set([MAsset.Key(assetID: "Cash")]) + + let bond = MAsset.Key(assetID: "Bond") + let equities = MAsset.Key(assetID: "Equities") + let gold = MAsset.Key(assetID: "Gold") + let re = MAsset.Key(assetID: "RE") + + func testNoPurchase() throws { + let map: RebalanceMap = [:] + let purchases = Purchase.getPurchases(rebalanceMap: map) + XCTAssertEqual(purchases.count, 0) + } + + func testOnePurchase() throws { + let map: RebalanceMap = [bond: 10] + let purchases = Purchase.getPurchases(rebalanceMap: map) + XCTAssertEqual(purchases.count, 1) + let expected = Purchase(assetKey: bond, amount: 10) + XCTAssertEqual(expected, purchases[0]) + } + + func testOnePurchaseIgnoreSale() throws { + let map: RebalanceMap = [bond: 10, equities: -10] + let purchases = Purchase.getPurchases(rebalanceMap: map) + XCTAssertEqual(purchases.count, 1) + let expected = Purchase(assetKey: bond, amount: 10) + XCTAssertEqual(expected, purchases[0]) + } + + func testOnePurchasePenny() throws { + let map: RebalanceMap = [bond: 0.01] + let purchases = Purchase.getPurchases(rebalanceMap: map) + XCTAssertEqual(purchases.count, 1) + let expected = Purchase(assetKey: bond, amount: 0.01) + XCTAssertEqual(expected, purchases[0]) + } + + func testOnePurchaseIgnoreLessThanPenny() throws { + let map: RebalanceMap = [bond: 0.00999] + let purchases = Purchase.getPurchases(rebalanceMap: map) + XCTAssertEqual(purchases.count, 0) + } + + func testIgnoreCash() throws { + let map: RebalanceMap = [cashAssetKey: 10] + let purchases = Purchase.getPurchases(rebalanceMap: map) + XCTAssertEqual(purchases.count, 0) + } + + func testSortedByAmountDesc() throws { + let map: RebalanceMap = [equities: 5, bond: 10, gold: 7, re: 6] + let purchases = Purchase.getPurchases(rebalanceMap: map) + XCTAssertEqual(purchases.count, 4) + let expected = [ + Purchase(assetKey: bond, amount: 10), + Purchase(assetKey: gold, amount: 7), + Purchase(assetKey: re, amount: 6), + Purchase(assetKey: equities, amount: 5), + ] + XCTAssertEqual(expected, purchases) + } +} diff --git a/Tests/Rebalance/GetRebalanceMapTests.swift b/Tests/Rebalance/GetRebalanceMapTests.swift new file mode 100644 index 0000000..b554e83 --- /dev/null +++ b/Tests/Rebalance/GetRebalanceMapTests.swift @@ -0,0 +1,344 @@ +// +// GetRebalanceMapTests.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// +// + +import XCTest + +import FlowBase +import AllocData + +@testable import FlowAllocLow + +class GetRebalanceMapTests: XCTestCase { + let modelJSON = """ + { + "assets": [ + { "title": "Bonds", "assetID": "Bond" }, + { "title": "SC Blend", "assetID": "SCBlend" }, + { "title": "SC Value", "assetID": "SCValue" }, + { "title": "Micro Cap", "assetID": "MicroCap" }, + { "title": "Total Market", "assetID": "TM" } + ], + "accounts": [ + { + "accountID": "1", + "title": "My First", + "isTaxable": false, + "canTrade": true + } + ], + "securities": [ + { "securityAssetID": "Bond", "securityID": "BND", "sharePrice": 1 }, + { "securityAssetID": "SCBlend", "securityID": "VB", "sharePrice": 1 }, + { "securityAssetID": "SCValue", "securityID": "VBR", "sharePrice": 1 }, + { "securityAssetID": "MicroCap", "securityID": "MC", "sharePrice": 1 }, + { "securityAssetID": "TM", "securityID": "VTI", "sharePrice": 1 } + ], + "caps": [], + "holdings": [], + "updatedAt": 639202449, + "id": "97A51E12-BEA0-4A70-BC8C-B93F39213025", + "allocations": [], + "trackers": [], + "strategies": [], + "caps": [], + "transactions": [], + "valuationSnapshots": [], + "valuationAccounts": [], + "valuationCashflows": [], + "valuationPositions": [], + } + """ + + var model: BaseModel! + var accountPresentValueMap: AccountPresentValueMap! + var accountHoldingsSummaryMap: AccountAssetHoldingsSummaryMap! + + override func setUpWithError() throws { + model = try StorageManager.decode(fromJSON: modelJSON) + } + + func refreshMaps() { + accountPresentValueMap = MAccount.getAccountPresentValueMap(model.accounts.map(\.primaryKey), + model.makeAccountHoldingsMap(), + model.makeSecurityMap()) + accountHoldingsSummaryMap = HoldingsSummary.getAccountAssetSummaryMap(model.accounts.map(\.primaryKey), + model.makeAccountHoldingsMap(), + model.makeSecurityMap()) + } + + let bond = MAsset.Key(assetID: "Bond") + let account1 = MAccount.Key(accountID: "1") + let scblend = MAsset.Key(assetID: "SCBlend") + let scvalue = MAsset.Key(assetID: "SCValue") + let tm = MAsset.Key(assetID: "TM") + let microcap = MAsset.Key(assetID: "MicroCap") + + func testRelatedHolding() throws { + // fulfill SC Blend target by substituting the related SC Value, avoiding the trade + + let vbrHolding1 = MHolding(accountID: "1", securityID: "VBR", lotID: "", shareCount: 100.00, shareBasis: 1) + model.holdings = [vbrHolding1] + + let allocMap: AssetValueMap = [ + scblend: 0.5, + bond: 0.5, + ] + + refreshMaps() + let holdingsSummaryMap = accountHoldingsSummaryMap[account1]! + let pv = accountPresentValueMap[account1] ?? 0 + + // no substitution (control) + let mapA = getRebalanceMap(allocMap, holdingsSummaryMap, pv) + XCTAssertEqual(3, mapA.count) + XCTAssertEqual(-100, mapA[scvalue]) + XCTAssertEqual(50, mapA[bond]) + XCTAssertEqual(50, mapA[scblend]) + } + + func testRelatedHoldingGrandparent() throws { + // DO NOT fulfill totalMarket target by substituting the related SC Value, as it's two steps removed + + let vbrHolding1 = MHolding(accountID: "1", securityID: "VBR", lotID: "", shareCount: 100.00, shareBasis: 1) + model.holdings = [vbrHolding1] + + let allocMap: AssetValueMap = [ + tm: 0.5, + bond: 0.5, + ] + + refreshMaps() + let holdingsSummaryMap = accountHoldingsSummaryMap[account1]! + let pv = accountPresentValueMap[account1] ?? 0 + + // no substitution (control) + let mapA = getRebalanceMap(allocMap, holdingsSummaryMap, pv) + XCTAssertEqual(3, mapA.count) + XCTAssertEqual(-100, mapA[scvalue]) + XCTAssertEqual(50, mapA[bond]) + XCTAssertEqual(50, mapA[tm]) + } + + func testRelatedHoldingPartial() throws { + // avoid trades entirely by subsituting releated + + let bndHolding = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 30.00, shareBasis: 1) + let vbHolding = MHolding(accountID: "1", securityID: "VB", lotID: "", shareCount: 20.00, shareBasis: 1) + let vbrHolding = MHolding(accountID: "1", securityID: "VBR", lotID: "", shareCount: 10.00, shareBasis: 1) + model.holdings = [bndHolding, vbHolding, vbrHolding] + + let allocMap: AssetValueMap = [ + scblend: 0.5, + bond: 0.5, + ] + + refreshMaps() + let holdingsSummaryMap = accountHoldingsSummaryMap[account1]! + let pv = accountPresentValueMap[account1] ?? 0 + + // no substitution (control) + let mapA = getRebalanceMap(allocMap, holdingsSummaryMap, pv) + XCTAssertEqual(2, mapA.count) + XCTAssertEqual(-10, mapA[scvalue]) + XCTAssertEqual(10, mapA[scblend]) + } + + func testDumpRelated() throws { + // dump related, as it's not needed (keeping the primary) + + let bndHolding = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 40.00, shareBasis: 1) + let vbHolding = MHolding(accountID: "1", securityID: "VB", lotID: "", shareCount: 50.00, shareBasis: 1) + let vbrHolding = MHolding(accountID: "1", securityID: "VBR", lotID: "", shareCount: 10.00, shareBasis: 1) + model.holdings = [bndHolding, vbHolding, vbrHolding] + + let allocMap: AssetValueMap = [ + scblend: 0.5, + bond: 0.5, + ] + + refreshMaps() + let holdingsSummaryMap = accountHoldingsSummaryMap[account1]! + let pv = accountPresentValueMap[account1] ?? 0 + + // no substitution (control) + let mapA = getRebalanceMap(allocMap, holdingsSummaryMap, pv) + + XCTAssertEqual(2, mapA.count) + XCTAssertEqual(10, mapA[bond]) + XCTAssertEqual(-10, mapA[scvalue]) + } + + func testRelatedOnePurchaseTwoSales() throws { + // avoid trades with two related holdings + + let bndHolding = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 40.00, shareBasis: 1) + let vbHolding = MHolding(accountID: "1", securityID: "VB", lotID: "", shareCount: 20.00, shareBasis: 1) + let vbrHolding = MHolding(accountID: "1", securityID: "VBR", lotID: "", shareCount: 10.00, shareBasis: 1) + let mcHolding = MHolding(accountID: "1", securityID: "MC", lotID: "", shareCount: 10.00, shareBasis: 1) + model.holdings = [bndHolding, vbHolding, vbrHolding, mcHolding] + + let allocMap: AssetValueMap = [ + scblend: 0.5, + bond: 0.5, + ] + + refreshMaps() + let holdingsSummaryMap = accountHoldingsSummaryMap[account1]! + let pv = accountPresentValueMap[account1] ?? 0 + + // no substitution (control) + let mapA = getRebalanceMap(allocMap, holdingsSummaryMap, pv) + + XCTAssertEqual(3, mapA.count) + XCTAssertEqual(-10, mapA[scvalue]) + XCTAssertEqual(-10, mapA[microcap]) + XCTAssertEqual(20, mapA[scblend]) + } + + func testRelatedTwoPurchasesOneSale() throws { + // avoid trades with two related holdings + + let bndHolding = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 40.00, shareBasis: 1) + let vbHolding = MHolding(accountID: "1", securityID: "VB", lotID: "", shareCount: 20.00, shareBasis: 1) + let vbrHolding = MHolding(accountID: "1", securityID: "VBR", lotID: "", shareCount: 10.00, shareBasis: 1) + let mcHolding = MHolding(accountID: "1", securityID: "MC", lotID: "", shareCount: 10.00, shareBasis: 1) + model.holdings = [bndHolding, vbHolding, vbrHolding, mcHolding] + + let allocMap: AssetValueMap = [ + scvalue: 0.25, + microcap: 0.25, + bond: 0.5, + ] + + refreshMaps() + let holdingsSummaryMap = accountHoldingsSummaryMap[account1]! + let pv = accountPresentValueMap[account1] ?? 0 + + // no substitution (control) + let mapA = getRebalanceMap(allocMap, holdingsSummaryMap, pv) + + XCTAssertEqual(3, mapA.count) + XCTAssertEqual(10, mapA[scvalue]) + XCTAssertEqual(10, mapA[microcap]) + XCTAssertEqual(-20, mapA[scblend]) + } + + // WARNING: sensitive to sort of asset classes in adjustForRelated + func testRetainAssetClassWithLargeGain() throws { + // avoid trades with two related holdings + + let bndHolding = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 40.00, shareBasis: 1) + let vbHolding = MHolding(accountID: "1", securityID: "VB", lotID: "", shareCount: 30.00, shareBasis: 1) + let vbrHolding = MHolding(accountID: "1", securityID: "VBR", lotID: "", shareCount: 10.00, shareBasis: 0.1) // large gain; should try to eliminate Microcaps BEFORE SmallCapValue + let mcHolding = MHolding(accountID: "1", securityID: "MC", lotID: "", shareCount: 10.00, shareBasis: 1.0) + model.holdings = [bndHolding, vbHolding, vbrHolding, mcHolding] + + let allocMap: AssetValueMap = [ + scblend: 0.5, + bond: 0.5, + ] + + refreshMaps() + let holdingsSummaryMap = accountHoldingsSummaryMap[account1]! + let pv = accountPresentValueMap[account1] ?? 0 + + // no substitution (control) + let mapA = getRebalanceMap(allocMap, holdingsSummaryMap, pv) + + XCTAssertEqual(4, mapA.count) + XCTAssertEqual(5, mapA[bond]) + XCTAssertEqual(-10, mapA[scvalue]) + XCTAssertEqual(-10, mapA[microcap]) + XCTAssertEqual(15, mapA[scblend]) + } + + func testExclusionNoProtection() throws { + let bndHolding = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 40.00, shareBasis: 1) + let vbHolding = MHolding(accountID: "1", securityID: "VB", lotID: "", shareCount: 20.00, shareBasis: 1) + let vbrHolding = MHolding(accountID: "1", securityID: "VBR", lotID: "", shareCount: 10.00, shareBasis: 1) + let mcHolding = MHolding(accountID: "1", securityID: "MC", lotID: "", shareCount: 10.00, shareBasis: 1) + model.holdings = [bndHolding, vbHolding, vbrHolding, mcHolding] + + let allocMap: AssetValueMap = [ + scvalue: 0.25, + microcap: 0.25, + bond: 0.5, + ] + + refreshMaps() + let holdingsSummaryMap = accountHoldingsSummaryMap[account1]! + let pv = accountPresentValueMap[account1] ?? 0 + + // no substitution (control) + let mapA = getRebalanceMap(allocMap, holdingsSummaryMap, pv) + + XCTAssertEqual(3, mapA.count) + XCTAssertEqual(10, mapA[scvalue]) // will be absorbed into blend + XCTAssertEqual(10, mapA[microcap]) // will be absorbed into blend + XCTAssertEqual(-20, mapA[scblend]) + } + + func testExclusionWithProtection() throws { + // NO substitution if both liquidating and acquiring asset classes in allocation + + let bndHolding = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 40.00, shareBasis: 1) + let vbHolding = MHolding(accountID: "1", securityID: "VB", lotID: "", shareCount: 20.00, shareBasis: 1) + let vbrHolding = MHolding(accountID: "1", securityID: "VBR", lotID: "", shareCount: 10.00, shareBasis: 1) + let mcHolding = MHolding(accountID: "1", securityID: "MC", lotID: "", shareCount: 10.00, shareBasis: 1) + model.holdings = [bndHolding, vbHolding, vbrHolding, mcHolding] + + let allocMap: AssetValueMap = [ + scblend: 0.25, + microcap: 0.25, + bond: 0.5, + ] + + refreshMaps() + let holdingsSummaryMap = accountHoldingsSummaryMap[account1]! + let pv = accountPresentValueMap[account1] ?? 0 + + // no substitution (control) + let mapA = getRebalanceMap(allocMap, holdingsSummaryMap, pv) + + XCTAssertEqual(2, mapA.count) + XCTAssertEqual(-10, mapA[scvalue]) + XCTAssertEqual(10, mapA[microcap]) + } + + func testExcludeRelatedParentAssetClass() throws { + // "SCValue" should be absorbed into "SCBlend" + // totalMarket should NOT be absorbed into "SCBlend" (because it's a parent of it) + + let bndHolding = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 40.00, shareBasis: 1) + let vtiHolding = MHolding(accountID: "1", securityID: "VTI", lotID: "", shareCount: 10.00, shareBasis: 1) + let vbHolding = MHolding(accountID: "1", securityID: "VB", lotID: "", shareCount: 20.00, shareBasis: 1) + let vbrHolding = MHolding(accountID: "1", securityID: "VBR", lotID: "", shareCount: 10.00, shareBasis: 1) + model.holdings = [bndHolding, vtiHolding, vbHolding, vbrHolding] + + let allocMap: AssetValueMap = [ + scvalue: 0.25, + tm: 0.25, + bond: 0.5, + ] + + refreshMaps() + let holdingsSummaryMap = accountHoldingsSummaryMap[account1]! + let pv = accountPresentValueMap[account1] ?? 0 + + // no substitution (control) + let mapA = getRebalanceMap(allocMap, holdingsSummaryMap, pv) + + XCTAssertEqual(3, mapA.count) + XCTAssertEqual(10, mapA[scvalue]) + XCTAssertEqual(10, mapA[tm]) + XCTAssertEqual(-20, mapA[scblend]) + } +} diff --git a/Tests/Rebalance/GetSalesTests.swift b/Tests/Rebalance/GetSalesTests.swift new file mode 100644 index 0000000..f8500d7 --- /dev/null +++ b/Tests/Rebalance/GetSalesTests.swift @@ -0,0 +1,155 @@ +// +// BaseSaleTests.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import XCTest + +import FlowBase +import AllocData + +@testable import FlowAllocLow + +class GetSalesTests: XCTestCase { + let cashAssetKey = MAsset.Key(assetID: "Cash") + let cashAssetKeySet = Set([MAsset.Key(assetID: "Cash")]) + + let account1 = MAccount.Key(accountID: "1") + let account2 = MAccount.Key(accountID: "2") + let bond = MAsset.Key(assetID: "Bond") + let equities = MAsset.Key(assetID: "Equities") + let bnd = MSecurity.Key(securityID: "BND") + + var securityMap: SecurityMap! + + override func setUp() { + securityMap = MSecurity.makeAllocMap([MSecurity(securityID: "BND", sharePrice: 1), + MSecurity(securityID: "AGG", sharePrice: 1)]) + } + + func testNoSale() throws { + let rMap: RebalanceMap = [:] + let sMap: SecurityMap = [bnd: MSecurity(securityID: "BND", assetID: "Bond")] + let ahMap: AssetHoldingsMap = [bond: [MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 1)]] + let sales = Sale.getSales(rMap, ahMap, sMap) + XCTAssertEqual(sales.count, 0) + } + + func testOneSale() throws { + for amount in [10, 0.01] { + let h = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 1) + let rm: RebalanceMap = [MAsset.Key(assetID: "Bond"): -amount] + let sm = [bnd: MSecurity(securityID: "BND", assetID: "Bond", sharePrice: amount)] + let ah = [MAsset.Key(assetID: "Bond"): [h]] + let sales = Sale.getSales(rm, ah, sm) + XCTAssertEqual(sales.count, 1) + let pv = h.getPresentValue(securityMap)! + let lh = LiquidateHolding(h, presentValue: pv) + let expected = Sale(assetKey: bond, targetAmount: amount, liquidateHoldings: [lh]) + XCTAssertEqual(expected, sales[0]) + } + } + + func testOneSaleIgnorePurchase() throws { + let h1 = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 1) + let h2 = MHolding(accountID: "1", securityID: "VOO", lotID: "", shareCount: 1) + let rm: RebalanceMap = [bond: -10, equities: 10] + let sm = MSecurity.makeAllocMap([ + MSecurity(securityID: "BND", assetID: "Bond", sharePrice: 1), + MSecurity(securityID: "VOO", assetID: "equities", sharePrice: 1)]) + let ah = [bond: [h1], equities: [h2]] + let sales = Sale.getSales(rm, ah, sm) + XCTAssertEqual(sales.count, 1) + let pv = h1.getPresentValue(securityMap)! + let lh = LiquidateHolding(h1, presentValue: pv) + let expected = Sale(assetKey: MAsset.Key(assetID: "Bond"), targetAmount: 10, liquidateHoldings: [lh]) + XCTAssertEqual(expected, sales[0]) + } + + func testOneSaleIgnoreLessThanPenny() throws { + let amount = 0.00999 + let h = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 1) + let rm: RebalanceMap = [MAsset.Key(assetID: "Bond"): -amount] + let sm = [bnd: MSecurity(securityID: "BND", assetID: "Bond", sharePrice: amount)] + let ah = [MAsset.Key(assetID: "Bond"): [h]] + let sales = Sale.getSales(rm, ah, sm) + XCTAssertEqual(sales.count, 0) + } + + func testOneSaleIgnoreCash() throws { + let amount = 1.00 + let h = MHolding(accountID: "1", securityID: "SPAXX", lotID: "", shareCount: 1) + let rm: RebalanceMap = [cashAssetKey: -amount] + let sm = MSecurity.makeAllocMap([ + MSecurity(securityID: "SPAXX", assetID: "Cash", sharePrice: amount)]) + let ah = [cashAssetKey: [h]] + let sales = Sale.getSales(rm, ah, sm) + XCTAssertEqual(sales.count, 0) + } + + func testOneSaleIgnoreIfBelowMinimum() throws { + let minimumAmount = 1.01 + let amount = 1.00 + let h = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 1) + let rm: RebalanceMap = [MAsset.Key(assetID: "Bond"): -amount] + let sm = [bnd: MSecurity(securityID: "BND", assetID: "Bond", sharePrice: 1)] + let ah = [MAsset.Key(assetID: "Bond"): [h]] + let sales = Sale.getSales(rm, ah, sm, minimumSaleAmount: minimumAmount) + XCTAssertEqual(sales.count, 0) + } + + func testOneSaleAtMinimum() throws { + let minimumAmount = 1.00 + let amount = 1.00 + let h = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 1) + let rm: RebalanceMap = [MAsset.Key(assetID: "Bond"): -amount] + let sm = [bnd: MSecurity(securityID: "BND", assetID: "Bond", sharePrice: 1)] + let ah = [MAsset.Key(assetID: "Bond"): [h]] + let sales = Sale.getSales(rm, ah, sm, minimumSaleAmount: minimumAmount) + XCTAssertEqual(sales.count, 1) + let pv = h.getPresentValue(securityMap)! + let lh = LiquidateHolding(h, presentValue: pv) + let expected = Sale(assetKey: MAsset.Key(assetID: "Bond"), targetAmount: amount, liquidateHoldings: [lh]) + XCTAssertEqual(expected, sales[0]) + } + + func testNoSaleIfNoHoldings() throws { + let amount = 1.00 + let rm: RebalanceMap = [MAsset.Key(assetID: "Bond"): -amount] + let sm = [bnd: MSecurity(securityID: "BND", assetID: "Bond", sharePrice: 1)] + let ah: AssetHoldingsMap = [MAsset.Key(assetID: "Bond"): []] + let sales = Sale.getSales(rm, ah, sm) + XCTAssertEqual(sales.count, 0) + } + + func testWholeSaleIfPartialHoldings() throws { + let h = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 0.25) + let rm: RebalanceMap = [MAsset.Key(assetID: "Bond"): -1.00] + let sm = [bnd: MSecurity(securityID: "BND", assetID: "Bond", sharePrice: 1)] + let ah: AssetHoldingsMap = [MAsset.Key(assetID: "Bond"): [h]] + let sales = Sale.getSales(rm, ah, sm) + XCTAssertEqual(sales.count, 1) + let pv = h.getPresentValue(securityMap)! + let lh = LiquidateHolding(h, presentValue: pv) + let expected = Sale(assetKey: MAsset.Key(assetID: "Bond"), targetAmount: 1.00, liquidateHoldings: [lh]) + XCTAssertEqual(expected, sales[0]) + } + + func testFractionalSaleIfPartialHoldings() throws { + let h = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 2.00) + let rm: RebalanceMap = [MAsset.Key(assetID: "Bond"): -1.00] + let sm = [bnd: MSecurity(securityID: "BND", assetID: "Bond", sharePrice: 1)] + let ah: AssetHoldingsMap = [MAsset.Key(assetID: "Bond"): [h]] + let sales = Sale.getSales(rm, ah, sm) + XCTAssertEqual(sales.count, 1) + let pv = h.getPresentValue(securityMap)! + let lh = LiquidateHolding(h, presentValue: pv, fraction: 0.5) // only selling half of position + let expected = Sale(assetKey: MAsset.Key(assetID: "Bond"), targetAmount: 1.00, liquidateHoldings: [lh]) + XCTAssertEqual(expected, sales[0]) + } +} diff --git a/Tests/Rebalance/HoldingsSummaryTests.swift b/Tests/Rebalance/HoldingsSummaryTests.swift new file mode 100644 index 0000000..39fa544 --- /dev/null +++ b/Tests/Rebalance/HoldingsSummaryTests.swift @@ -0,0 +1,30 @@ +// +// HoldingsSummaryTests.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import XCTest + +import FlowBase +import AllocData + +@testable import FlowAllocLow + +class HoldingsSummaryTests: XCTestCase { + func testUnrealizedGain() throws { + let expected = 10.0 + let actual = HoldingsSummary(presentValue: 30, costBasis: 20).unrealizedGain + XCTAssertEqual(expected, actual) + } + + func testUnrealizedGainZeroForLoss() throws { + let expected = 0.0 + let actual = HoldingsSummary(presentValue: 10, costBasis: 20).unrealizedGain + XCTAssertEqual(expected, actual) + } +} diff --git a/Tests/Rebalance/LiquidateHoldingTests.swift b/Tests/Rebalance/LiquidateHoldingTests.swift new file mode 100644 index 0000000..78154bb --- /dev/null +++ b/Tests/Rebalance/LiquidateHoldingTests.swift @@ -0,0 +1,70 @@ +// +// LiquidateHoldingTests.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import XCTest + +import FlowBase +import AllocData + +@testable import FlowAllocLow + +class LiquidateHoldingTests: XCTestCase { + var securityMap: SecurityMap! + + override func setUp() { + securityMap = MSecurity.makeAllocMap( [ + MSecurity(securityID: "BND", sharePrice: 1), + MSecurity(securityID: "AGG", sharePrice: 1)]) + } + + func testFullWithGain() throws { + let h = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 2, shareBasis: 0.50) + let pv = h.getPresentValue(securityMap)! + let lh = LiquidateHolding(h, presentValue: pv, fraction: 1) // sell all of position + XCTAssertEqual(2.0, lh.presentValue) + XCTAssertEqual(1.0, lh.fraction) + XCTAssertEqual(1.0, lh.fractionalGainLoss) // 2 * (1 - 0.50) + XCTAssertEqual(2.0, lh.fractionalShareCount) + XCTAssertEqual(2.0, lh.fractionalValue) + } + + func testFullWithLoss() throws { + let h = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 2, shareBasis: 1.50) + let pv = h.getPresentValue(securityMap)! + let lh = LiquidateHolding(h, presentValue: pv, fraction: 1) // sell all of position + XCTAssertEqual(2.0, lh.presentValue) + XCTAssertEqual(1.0, lh.fraction) + XCTAssertEqual(-1.0, lh.fractionalGainLoss) // 2 * (1 - 1.50) + XCTAssertEqual(2.0, lh.fractionalShareCount) + XCTAssertEqual(2.0, lh.fractionalValue) + } + + func testHalfWithGain() throws { + let h = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 2, shareBasis: 0.50) + let pv = h.getPresentValue(securityMap)! + let lh = LiquidateHolding(h, presentValue: pv, fraction: 0.5) // sell half of position + XCTAssertEqual(2.0, lh.presentValue) + XCTAssertEqual(0.5, lh.fraction) + XCTAssertEqual(0.5, lh.fractionalGainLoss) // (2 * (1 - 0.50)) * 0.5 + XCTAssertEqual(1.0, lh.fractionalShareCount) + XCTAssertEqual(1.0, lh.fractionalValue) + } + + func testHalfWithLoss() throws { + let h = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 2, shareBasis: 1.50) + let pv = h.getPresentValue(securityMap)! + let lh = LiquidateHolding(h, presentValue: pv, fraction: 0.5) // sell half of position + XCTAssertEqual(2.0, lh.presentValue) + XCTAssertEqual(0.5, lh.fraction) + XCTAssertEqual(-0.5, lh.fractionalGainLoss) // (2 * (1 - 1.50)) * 0.5 + XCTAssertEqual(1.0, lh.fractionalShareCount) + XCTAssertEqual(1.0, lh.fractionalValue) + } +} diff --git a/Tests/Rebalance/MRebalancePurchaseMapTests.swift b/Tests/Rebalance/MRebalancePurchaseMapTests.swift new file mode 100644 index 0000000..16beadf --- /dev/null +++ b/Tests/Rebalance/MRebalancePurchaseMapTests.swift @@ -0,0 +1,84 @@ +// +// MRebalancePurchaseMapTests.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import XCTest + +import FlowBase +import AllocData + +@testable import FlowAllocLow + +class MRebalancePurchaseMapTests: XCTestCase { + + let account1 = MAccount.Key(accountID: "1") + let account2 = MAccount.Key(accountID: "2") + let bond = MAsset.Key(assetID: "Bond") + let equities = MAsset.Key(assetID: "Equities") + + + let accountMap: AccountMap = MAccount.makeAllocMap([ + MAccount(accountID: "1"), + MAccount(accountID: "2") + ]) + let assetMap: AssetMap = MAsset.makeAllocMap([ + MAsset(assetID: "Bond"), + MAsset(assetID: "Equities") + ]) + + func testNoAccounts() throws { + let map: AccountPurchasesMap = [:] + let purchases = MRebalancePurchase.getPurchases(map, accountMap, assetMap) + XCTAssertTrue(purchases.count == 0) + } + + func testSingleAccountNoPurchases() throws { + let map: AccountPurchasesMap = [MAccount.Key(accountID: "1"): []] + let purchases = MRebalancePurchase.getPurchases(map, accountMap, assetMap) + XCTAssertTrue(purchases.count == 0) + } + + func testSingleAccountOnePurchase() throws { + let purchase = Purchase(assetKey: bond, amount: 10) + let map: AccountPurchasesMap = [account1: [purchase]] + let actual = MRebalancePurchase.getPurchases(map, accountMap, assetMap) + let expected = [ + MRebalancePurchase(accountID: "1", assetID: "Bond", amount: 10) + ] + XCTAssertEqual(expected, actual) + } + + func testSingleAccountTwoPurchases() throws { + let purchase1 = Purchase(assetKey: bond, amount: 10) + let purchase2 = Purchase(assetKey: equities, amount: 13) + let map: AccountPurchasesMap = [account1: [purchase1, purchase2]] + let actual = MRebalancePurchase.getPurchases(map, accountMap, assetMap) + let expected = [ + MRebalancePurchase(accountID: "1", assetID: "Bond", amount: 10), + MRebalancePurchase(accountID: "1", assetID: "Equities", amount: 13) + ] + XCTAssertEqual(expected, actual) + } + + func testDualAccountTwoPurchases() throws { + let purchase1 = Purchase(assetKey: bond, amount: 10) + let purchase2 = Purchase(assetKey: equities, amount: 13) + let purchase3 = Purchase(assetKey: bond, amount: 20) + let purchase4 = Purchase(assetKey: equities, amount: 23) + let map: AccountPurchasesMap = [account1: [purchase1, purchase2], account2: [purchase3, purchase4]] + let actual = MRebalancePurchase.getPurchases(map, accountMap, assetMap) + let expected = [ + MRebalancePurchase(accountID: "1", assetID: "Bond", amount: 10), + MRebalancePurchase(accountID: "1", assetID: "Equities", amount: 13), + MRebalancePurchase(accountID: "2", assetID: "Bond", amount: 20), + MRebalancePurchase(accountID: "2", assetID: "Equities", amount: 23) + ] + XCTAssertEqual(Set(expected), Set(actual)) + } +} diff --git a/Tests/Rebalance/MRebalanceSaleMapTests.swift b/Tests/Rebalance/MRebalanceSaleMapTests.swift new file mode 100644 index 0000000..38af3c8 --- /dev/null +++ b/Tests/Rebalance/MRebalanceSaleMapTests.swift @@ -0,0 +1,124 @@ +// +// MRebalanceSaleMapTests.swift +// +// Copyright 2021, 2022 OpenAlloc LLC +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// + +import XCTest + +import FlowBase +import AllocData + +@testable import FlowAllocLow + +class MRebalanceSaleMapTests: XCTestCase { + + let account1 = MAccount.Key(accountID: "1") + let account2 = MAccount.Key(accountID: "2") + let bond = MAsset.Key(assetID: "Bond") + let equities = MAsset.Key(assetID: "Equities") + + func testNoAccounts() throws { + let map: AccountSalesMap = [:] + let purchases = MRebalanceSale.getSales(map) + XCTAssertTrue(purchases.count == 0) + } + + func testSingleAccountNoSales() throws { + let map: AccountSalesMap = [account1: []] + let purchases = MRebalanceSale.getSales(map) + XCTAssertTrue(purchases.count == 0) + } + + func testSingleAccountOneSaleNoLH() throws { + let sale = Sale(assetKey: bond, targetAmount: 10) + let map: AccountSalesMap = [account1: [sale]] + let actual = MRebalanceSale.getSales(map) + let expected: [MRebalanceSale] = [] + XCTAssertEqual(expected, actual) + } + + func testSingleAccountOneSaleWithOneLH() throws { + let holding = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 1) + let lh = LiquidateHolding(holding, presentValue: 20, fraction: 1.0) + let sale = Sale(assetKey: bond, targetAmount: 0, liquidateHoldings: [lh]) + let map: AccountSalesMap = [account1: [sale]] + let actual = MRebalanceSale.getSales(map) + let expected: [MRebalanceSale] = [ + MRebalanceSale(accountID: "1", securityID: "BND", lotID: "", amount: 20.00, shareCount: 1, liquidateAll: true) + ] + XCTAssertEqual(expected, actual) + } + + func testSingleAccountOneSaleWithOneLHPartial() throws { + let fraction = 0.2 + let holding = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 3) + let lh = LiquidateHolding(holding, presentValue: 20, fraction: fraction) // partial! + let sale = Sale(assetKey: bond, targetAmount: 0, liquidateHoldings: [lh]) + let map: AccountSalesMap = [account1: [sale]] + let actual = MRebalanceSale.getSales(map) + let expected: [MRebalanceSale] = [ + MRebalanceSale(accountID: "1", securityID: "BND", lotID: "", amount: 20 * fraction, shareCount: 3.0 * fraction, liquidateAll: false) + ] + XCTAssertEqual(expected, actual) + } + + func testSingleAccountOneSaleWithTwoLHs() throws { + let holding1 = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 1) + let holding2 = MHolding(accountID: "1", securityID: "AGG", lotID: "", shareCount: 2) + let lh1 = LiquidateHolding(holding1, presentValue: 10, fraction: 1.0) + let lh2 = LiquidateHolding(holding2, presentValue: 20, fraction: 1.0) + let sale = Sale(assetKey: bond, targetAmount: 0, liquidateHoldings: [lh1, lh2]) + let map: AccountSalesMap = [account1: [sale]] + let actual = MRebalanceSale.getSales(map) + let expected: [MRebalanceSale] = [ + MRebalanceSale(accountID: "1", securityID: "BND", lotID: "", amount: 10.00, shareCount: 1, liquidateAll: true), + MRebalanceSale(accountID: "1", securityID: "AGG", lotID: "", amount: 20.00, shareCount: 2, liquidateAll: true) + ] + XCTAssertEqual(expected, actual) + } + + func testSingleAccountTwoSaleWithOneLH() throws { + let holding1 = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 1) + let holding2 = MHolding(accountID: "1", securityID: "SPY", lotID: "", shareCount: 2) + let lh1 = LiquidateHolding(holding1, presentValue: 10, fraction: 1.0) + let lh2 = LiquidateHolding(holding2, presentValue: 20, fraction: 1.0) + let sale1 = Sale(assetKey: bond, targetAmount: 0, liquidateHoldings: [lh1]) + let sale2 = Sale(assetKey: equities, targetAmount: 0, liquidateHoldings: [lh2]) + let map: AccountSalesMap = [account1: [sale1, sale2]] + let actual = MRebalanceSale.getSales(map) + let expected: [MRebalanceSale] = [ + MRebalanceSale(accountID: "1", securityID: "BND", lotID: "", amount: 10.00, shareCount: 1, liquidateAll: true), + MRebalanceSale(accountID: "1", securityID: "SPY", lotID: "", amount: 20.00, shareCount: 2, liquidateAll: true) + ] + XCTAssertEqual(expected, actual) + } + + + func testDualAccountDualSaleWithTwoLHs() throws { + let holding1 = MHolding(accountID: "1", securityID: "BND", lotID: "", shareCount: 1) + let holding2 = MHolding(accountID: "1", securityID: "AGG", lotID: "", shareCount: 2) + let holding3 = MHolding(accountID: "2", securityID: "BND", lotID: "", shareCount: 5) + let holding4 = MHolding(accountID: "2", securityID: "AGG", lotID: "", shareCount: 7) + let lh1 = LiquidateHolding(holding1, presentValue: 10, fraction: 1.0) + let lh2 = LiquidateHolding(holding2, presentValue: 20, fraction: 1.0) + let lh3 = LiquidateHolding(holding3, presentValue: 50, fraction: 1.0) + let lh4 = LiquidateHolding(holding4, presentValue: 70, fraction: 1.0) + let sale1 = Sale(assetKey: bond, targetAmount: 0, liquidateHoldings: [lh1, lh2]) + let sale2 = Sale(assetKey: bond, targetAmount: 0, liquidateHoldings: [lh3, lh4]) + let map: AccountSalesMap = [account1: [sale1], account2: [sale2]] + let actual = MRebalanceSale.getSales(map) + let expected: [MRebalanceSale] = [ + MRebalanceSale(accountID: "1", securityID: "BND", lotID: "", amount: 10.00, shareCount: 1, liquidateAll: true), + MRebalanceSale(accountID: "1", securityID: "AGG", lotID: "", amount: 20.00, shareCount: 2, liquidateAll: true), + MRebalanceSale(accountID: "2", securityID: "BND", lotID: "", amount: 50.00, shareCount: 5, liquidateAll: true), + MRebalanceSale(accountID: "2", securityID: "AGG", lotID: "", amount: 70.00, shareCount: 7, liquidateAll: true), + ] + XCTAssertEqual(Set(expected), Set(actual)) + } + +}