Skip to content

Instantly share code, notes, and snippets.

@abel30567
Forked from anthonytxie/hodl20.py
Created May 14, 2018 22:15
Show Gist options
  • Save abel30567/060c861a8e8db6f1ab6f88febbb78c8c to your computer and use it in GitHub Desktop.
Save abel30567/060c861a8e8db6f1ab6f88febbb78c8c to your computer and use it in GitHub Desktop.
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