Balance management after (partial) Asset buy/sell
Hello,
Which is the best way to record a partial asset sale? For example: I own some shares bought at price "X$" now the value of these shares is "(X+100)$" and I sold them at "(X+50)$". How can I record this transaction without go negative in asset balance?
I think that the balance should be automatically managed as much as possible.
For this purpose the asset balance could be designed to store the quantity of that asset (shares, options etc).
Follow a minimal playground example:
typealias Shares = Double
typealias Euros = Double
typealias Dollars = Double
enum Assets { case AAPL, MSFT, AMZN, GOOG }
struct Balance: CustomStringConvertible {
var description: String {
return "Payment Account: \(payment_account) \nAssets: \(assets.description)"
}
var payment_account:Dollars = 1500
var assets: [Assets:Shares] = [Assets.MSFT:100]
private mutating func createAsset(kind:Assets, amount:Shares) {
assets[kind] = amount
}
mutating func buy(quantity: Shares, of kind: Assets, for value:Dollars) {
assert(quantity > 0 && value > 0 && payment_account >= value*quantity)
if let old_value = assets[kind] {
assets[kind] = old_value + quantity
} else {
createAsset(kind: kind, amount: quantity)
}
payment_account -= value*quantity
}
mutating func sell(quantity: Shares, of kind: Assets, for value:Dollars) {
assert(quantity > 0 && value > 0)
if let old_value = assets[kind] {
assert(old_value >= quantity)
assets[kind] = old_value - quantity
payment_account += value*quantity
}
}
}
var my_balance = Balance()
print(my_balance)
my_balance.buy(quantity: 10, of: .AAPL, for: 100)
print(my_balance)
my_balance.sell(quantity: 5, of: .AAPL, for: 150)
print(my_balance)
The output will be:
Payment Account: 1500.0
Assets: [MSFT: 100.0]
Payment Account: 500.0
Assets: [AAPL: 10.0, MSFT: 100.0]
Payment Account: 1250.0
Assets: [AAPL: 5.0, MSFT: 100.0]
Thanks,
Simone
0
Zaloguj się, aby dodać komentarz.
Komentarze
Komentarze: 0