Instantly share code, notes, and snippets.

Embed
What would you like to do?
Hodl 20 Rebalancing Algorithm
def calc_allocations(self, date, quantity, cap):
"""Figure out ideal allocations for a given date"""
# {
# coin_name: (percent_allocation, data)
# }
top_market = self.get_top_market(date, quantity)
total_cap = sum([coin.market_cap for coin in top_market])
allocations = [{
'market_cap': coin.market_cap,
'symbol': coin.name,
'ratio': (coin.market_cap / total_cap) # ratios (sums to 100%)
} for coin in top_market]
allocations = list(sorted(allocations, key=lambda alloc: -alloc['ratio'])) # sort by descending ratio
for i in range(len(allocations)):
alloc = allocations[i]
if alloc['ratio'] > cap:
overflow = alloc['ratio'] - cap # the amount of % that needs to be spread to the other coins
alloc['ratio'] = cap
remaining_allocs = allocations[i+1:]
total_nested_cap = sum([n_alloc['market_cap'] for n_alloc in remaining_allocs]) # market cap of the remaining coins
new_allocs = list()
for n_alloc in remaining_allocs:
cap_fraction = n_alloc['market_cap'] / total_nested_cap # percentage of the remainder this makes up (sums to 100%)
n_alloc['ratio'] += overflow * cap_fraction # weighted
new_allocs.append(n_alloc)
allocations = allocations[:i+1] + new_allocs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment