create account

Calculate the APR of your delegations (not dlease) by gadrian

View this thread on: hive.blogpeakd.comecency.com
@gadrian (edited)
$5.56
Calculate the APR of your delegations (not dlease)
A while ago I found myself looking for a tool to easily calculate the APR for my delegations which paid something back.

I'm not talking about dlease delegations, because their site is well crafted and the APR is in the center of it, both for the delegators and for the delegatees.

But you might delegate to other services which also share all or part of the ROI generated from the delegation you offered.

So after not finding what I was looking for, I decided to make my own script to calculate the APRs of the delegations.

The script is written in Python and I'll share it with you below. You are free to play around with it and adapt it to your needs.

### What can you do with the script?

* calculate APRs for the delegations from one account to a number of specified accounts (introduced as a comma-separated list; note: accounts from the list are not tested if they are real Hive accounts, typos will generate a <code>KeyError</code> error)
* delegations updates between start date and stop date are tracked and APR is calculated for each distinct period
* the algorithm allows different delegatees and paying accounts

### Limitations

* something I haven't added in the script although I should have is a distinction between HIVE and HBD for payments received. I wasn't bothered because all my payments were received in HIVE.
* it doesn't work for delegations via dlease or any other systems where delegations to different accounts are aggregated when payment is being made
* it doesn't take into account the 5 days cooldown period when calculating the APR
* it doesn't work if payment is being made to a different account than the one from which the delegations are being made (this can of course be added but I didn't)

### Python Script

```
import sys
from beem import Hive
from beem.account import Account
from beem.nodelist import NodeList
import time
from datetime import datetime, timedelta
from datetime import date

if __name__ == "__main__":
    nodelist = NodeList()
    nodelist.update_nodes()
    blockchain_instance = Hive(node=nodelist.get_hive_nodes())    
    assert blockchain_instance.is_hive

    your_account_name = input("Enter your account name: ")
    try:
        your_account = Account(your_account_name, blockchain_instance=blockchain_instance)
    except:
        print('Something went wrong! Does the account exist on Hive? Check the spelling!')
        sys.exit()

    delegatee_accounts_names = []
    delegatee_accounts_names_str = input("Delegations to calculate APR for (comma-separated list, i.e.: account1, account2, account3): ")
    delegatee_accounts_names = delegatee_accounts_names_str.strip().split(',')
    paying_accounts_names = {}
    for delegatee_account_name in delegatee_accounts_names:
        delegatee_accounts_names[delegatee_accounts_names.index(delegatee_account_name)] = delegatee_account_name.strip()
        delegatee_account_name = delegatee_account_name.strip()
        paying_account_name = input('Enter paying account name for delegation at %s (leave empty if it\'s the same): ' % delegatee_account_name)
        if paying_account_name == "":
            paying_account_name = delegatee_account_name
        paying_accounts_names[delegatee_account_name] = paying_account_name
    print('Paying accounts: %s' % paying_accounts_names)

    print('----')
    print('Make sure the start date is older than the first delegation you included in the analysis!')
    print('Otherwise your first delegation operation won\'t be found, because the algorithm doesn\'t look in reverse history from the start date.')
    start_date_str = input('Enter start date (YY-MM-DD): ')
    start_date = datetime.strptime(start_date_str, '%y-%m-%d')
    stop_date_str = input('Enter stop date (YY-MM-DD, leave empty for today): ')
    if stop_date_str == "":
        stop_date = datetime.combine(date.today(), datetime.min.time())
    else:
        stop_date = datetime.strptime(stop_date_str, '%y-%m-%d')

    # transactions        
    acc_op = ['transfer', 'delegate_vesting_shares']

    current_start_date = {}
    current_stop_date = {}
    current_delegated_amount_hp = {}

    current_total_amount_received = {}

    for transactions in your_account.history(start_date, stop_date, use_block_num=False, only_ops=acc_op):
        if transactions['type'] == 'delegate_vesting_shares':
            if transactions['delegator'] != your_account_name:
                continue
            if transactions['delegatee'] not in delegatee_accounts_names:
                continue
            delegatee_account_name = transactions['delegatee']
            if delegatee_account_name in current_start_date:
                print('----')
                print('APR before the delegation update for %s:' % delegatee_account_name)
                current_stop_date[delegatee_account_name] = datetime.strptime(transactions['timestamp'], '%Y-%m-%dT%H:%M:%S')
                delta = current_stop_date[delegatee_account_name] - current_start_date[delegatee_account_name] #+ timedelta(days=5) # timedelta = 5 days cooldown
                if current_delegated_amount_hp[delegatee_account_name] > 0 and delta.days > 0:
                    apr = float(current_total_amount_received[paying_accounts_names[delegatee_account_name]] / current_delegated_amount_hp[delegatee_account_name] * 365 / delta.days * 100)
                else:
                    apr = -1.0 # if delegation or period is zero
                print('%s had delegated %.3f HP to %s at %s' % (your_account_name, current_delegated_amount_hp[delegatee_account_name], delegatee_account_name, current_start_date[delegatee_account_name]))
                print('Delegation date: %s' % current_start_date[delegatee_account_name])
                print('Stop date: %s' % current_stop_date[delegatee_account_name])
                print('Period (in days): %s' % delta.days)        
                print('Total amount received by %s from %s for delegation to % s, in the given period: %.3f HIVE' % (your_account_name, paying_accounts_names[delegatee_account_name], delegatee_account_name, current_total_amount_received[paying_accounts_names[delegatee_account_name]]))
                if apr != -1.0:
                    print('APR during the period=%.2f%%' % apr)
                else:
                    print('APR: Undefined - either the period or the delegation is zero!')
                
                current_start_date[delegatee_account_name] = current_stop_date[delegatee_account_name]                
                current_stop_date[delegatee_account_name] = stop_date

                current_total_amount_received[delegatee_account_name] = 0.0
            else:
                current_start_date[delegatee_account_name] = datetime.strptime(transactions['timestamp'], '%Y-%m-%dT%H:%M:%S')                
                current_stop_date[delegatee_account_name] = stop_date
            current_delegated_amount_hp[delegatee_account_name] = (float(transactions['vesting_shares']['amount']) / 1000000) * (blockchain_instance.get_hive_per_mvest() / 1000000)
            
        
        if transactions['type'] == 'transfer':
            if transactions['from'] not in paying_accounts_names.values():
                continue
            if transactions['from'] in current_total_amount_received:
                current_total_amount_received[transactions['from']] += float(transactions['amount']['amount']) / 1000
            else:
                current_total_amount_received[transactions['from']] = float(transactions['amount']['amount']) / 1000

    for delegatee_account_name in delegatee_accounts_names:        
        delta = current_stop_date[delegatee_account_name] - current_start_date[delegatee_account_name] #+ timedelta(days=5) # timedelta = 5 days cooldown
        if current_delegated_amount_hp[delegatee_account_name] > 0 and delta.days > 0:
            apr = float(current_total_amount_received[paying_accounts_names[delegatee_account_name]] / current_delegated_amount_hp[delegatee_account_name] * 365 / delta.days * 100)
        else:
            apr = -1.0 # if delegation or period is zero
        
        print('----')
        print('%s delegated %.3f HP to %s at %s' % (your_account_name, current_delegated_amount_hp[delegatee_account_name], delegatee_account_name, current_start_date[delegatee_account_name]))
        print('Delegation date: %s' % current_start_date[delegatee_account_name])
        print('Stop date: %s' % current_stop_date[delegatee_account_name])
        print('Period (in days): %s' % delta.days)        
        print('Total amount received by %s from %s for delegation to % s, in the given period: %.3f HIVE' % (your_account_name, paying_accounts_names[delegatee_account_name], delegatee_account_name, current_total_amount_received[paying_accounts_names[delegatee_account_name]]))
        if apr != -1.0:
            print('APR during the period=%.2f%%' % apr)
        else:
            print('APR: Undefined - either the period or the delegation is zero!')
```
*Code EDIT: Removed the unnecessary posting key request and making a few print outputs a little clearer.*
馃憤  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
馃憥  
properties (23)
authorgadrian
permlinkcalculate-the-apr-of-your-delegations-not-dlease
categoryhive-139531
json_metadata"{"app":"peakd/2020.06.1","format":"markdown","description":"You can calculate the APR of your delegations (other than dlease) using this Python script.","tags":["delegations-apr","python","leofinance"],"image":[]}"
created2020-06-16 12:55:54
last_update2020-06-17 09:16:33
depth0
children7
last_payout2020-06-23 12:55:54
cashout_time1969-12-31 23:59:59
total_payout_value2.871 HBD
curator_payout_value2.688 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length9,126
author_reputation643,815,277,325,139
root_title"Calculate the APR of your delegations (not dlease)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id97,999,106
net_rshares13,623,326,395,133
author_curate_reward""
vote details (64)
@chitty
I have picked your post for my daily hive voting initiative, Keep it up and Hive On!!
properties (22)
authorchitty
permlinkre-calculate-the-apr-of-your-delegations-not-dlease-20200617t000520
categoryhive-139531
json_metadata""
created2020-06-17 00:05:21
last_update2020-06-17 00:05:21
depth1
children1
last_payout2020-06-24 00:05:21
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length86
author_reputation86,901,300,608,582
root_title"Calculate the APR of your delegations (not dlease)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,009,329
net_rshares0
@gadrian
Thanks!
properties (22)
authorgadrian
permlinkre-chitty-qc2a01
categoryhive-139531
json_metadata{"tags":["hive-139531"],"app":"peakd/2020.05.5"}
created2020-06-17 08:24:03
last_update2020-06-17 08:24:03
depth2
children0
last_payout2020-06-24 08:24:03
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length7
author_reputation643,815,277,325,139
root_title"Calculate the APR of your delegations (not dlease)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,014,671
net_rshares0
@crokkon (edited)
$0.02
.
.
馃憤  
properties (23)
authorcrokkon
permlinkre-gadrian-qc1aah
categoryhive-139531
json_metadata"{"app": ""}"
created2020-06-16 19:32:33
last_update2022-08-06 16:02:57
depth1
children1
last_payout2020-06-23 19:32:33
cashout_time1969-12-31 23:59:59
total_payout_value0.010 HBD
curator_payout_value0.010 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1
author_reputation81,214,366,861,104
root_title"Calculate the APR of your delegations (not dlease)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,005,507
net_rshares82,839,061,093
author_curate_reward""
vote details (1)
@gadrian
Yep, you are right! I reused a script and forgot to take that part out. Thanks for pointing it out.
properties (22)
authorgadrian
permlinkre-crokkon-2020616t23504537z
categoryhive-139531
json_metadata{"tags":["hive-139531"],"app":"esteem/2.2.5-mobile","format":"markdown+html","community":"hive-125125"}
created2020-06-16 20:50:45
last_update2020-06-16 20:50:45
depth2
children0
last_payout2020-06-23 20:50:45
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length99
author_reputation643,815,277,325,139
root_title"Calculate the APR of your delegations (not dlease)"
beneficiaries
0.
accountesteemapp
weight300
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,006,804
net_rshares0
@gitplait-mod1
$0.03
This is the way to go. Make your own path to move forward. Your efforts are laudable. It will be helpful for the people who are looking for APR Calculations. Keep it up your good work. Gitplait is looking for a user kike you. 

Your post has been curated with @gitplait community account because this is the kind of publications we like to see in our community.

Join our Community on [Hive](https://hive.blog/trending/hive-103590) and Chat with us on [Discord](https://discord.com/invite/CWCj3rw).

[Gitplait-Team]
馃憤  ,
properties (23)
authorgitplait-mod1
permlinkqc0sm7
categoryhive-139531
json_metadata{"users":["gitplait"],"links":["https://hive.blog/trending/hive-103590","https://discord.com/invite/CWCj3rw"],"app":"hiveblog/0.1"}
created2020-06-16 13:10:57
last_update2020-06-16 13:10:57
depth1
children1
last_payout2020-06-23 13:10:57
cashout_time1969-12-31 23:59:59
total_payout_value0.014 HBD
curator_payout_value0.014 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length515
author_reputation64,455,719,431
root_title"Calculate the APR of your delegations (not dlease)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id97,999,340
net_rshares111,755,682,235
author_curate_reward""
vote details (2)
@gadrian
Thanks, appreciate it!
properties (22)
authorgadrian
permlinkre-gitplait-mod1-qc0zsf
categoryhive-139531
json_metadata{"tags":["hive-139531"],"app":"peakd/2020.05.5"}
created2020-06-16 15:45:54
last_update2020-06-16 15:45:54
depth2
children0
last_payout2020-06-23 15:45:54
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length22
author_reputation643,815,277,325,139
root_title"Calculate the APR of your delegations (not dlease)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,002,013
net_rshares0
@hivebuzz
Congratulations @gadrian! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s) :

<table><tr><td><img src="https://images.hive.blog/60x70/http://hivebuzz.me/@gadrian/replies.png?202006181555"></td><td>You got more than 3250 replies. Your next target is to reach 3500 replies.</td></tr>
</table>

<sub>_You can view [your badges on your board](https://hivebuzz.me/@gadrian) And compare to others on the [Ranking](https://hivebuzz.me/ranking)_</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>



###### Support the HiveBuzz project. [Vote](https://hivesigner.com/sign/update_proposal_votes?proposal_ids=%5B%22109%22%5D&approve=true) for [our proposal](https://peakd.com/me/proposals/109)!
properties (22)
authorhivebuzz
permlinkhivebuzz-notify-gadrian-20200618t162756000z
categoryhive-139531
json_metadata{"image":["http://hivebuzz.me/notify.t6.png"]}
created2020-06-18 16:27:57
last_update2020-06-18 16:27:57
depth1
children0
last_payout2020-06-25 16:27:57
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length803
author_reputation369,874,061,244,718
root_title"Calculate the APR of your delegations (not dlease)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,041,396
net_rshares0