Created
October 14, 2024 07:20
-
-
Save oNddleo/23a794a86f25bee7ebefbd518b0c06fa to your computer and use it in GitHub Desktop.
rebalance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
// TickerAllocation represents a ticker symbol and its allocation percentage. | |
type TickerAllocation struct { | |
Ticker string | |
Allocation float64 | |
} | |
// Instruction represents a buy or sell instruction. | |
type Instruction struct { | |
Ticker string | |
Action string // "BUY" or "SELL" | |
Amount float64 | |
} | |
// Rebalance generates buy or sell instructions to align current with target allocations. | |
func Rebalance(current, target []TickerAllocation) []Instruction { | |
// Create maps for quick lookup by ticker symbol. | |
currentMap := make(map[string]float64) | |
for _, c := range current { | |
currentMap[c.Ticker] = c.Allocation | |
} | |
instructions := []Instruction{} | |
// Iterate over the target allocation and compare with current holdings. | |
for _, t := range target { | |
currAlloc := currentMap[t.Ticker] | |
diff := t.Allocation - currAlloc | |
if math.Abs(diff) > 0.01 { // Ignore small differences. | |
action := "BUY" | |
if diff < 0 { | |
action = "SELL" | |
diff = -diff | |
} | |
instructions = append(instructions, Instruction{ | |
Ticker: t.Ticker, | |
Action: action, | |
Amount: diff, | |
}) | |
} | |
// Remove processed ticker from the currentMap to track leftovers. | |
delete(currentMap, t.Ticker) | |
} | |
// Any remaining tickers in currentMap need to be sold completely. | |
for ticker, alloc := range currentMap { | |
if alloc > 0 { | |
instructions = append(instructions, Instruction{ | |
Ticker: ticker, | |
Action: "SELL", | |
Amount: alloc, | |
}) | |
} | |
} | |
return instructions | |
} | |
func main() { | |
// Example input: Current holdings with their allocations. | |
current := []TickerAllocation{ | |
{"AAPL", 30}, | |
{"GOOG", 20}, | |
{"AMZN", 50}, | |
} | |
// Example target allocations. | |
target := []TickerAllocation{ | |
{"AAPL", 25}, | |
{"TSLA", 35}, | |
{"GOOG", 40}, | |
} | |
// Call the rebalance function. | |
instructions := Rebalance(current, target) | |
// Output the instructions. | |
fmt.Println("Rebalance Instructions:") | |
for _, instr := range instructions { | |
fmt.Printf("%s %s %.2f%%\n", instr.Action, instr.Ticker, instr.Amount) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment