create account

Part 20: Plotting Account's Total Generated Post Rewards Since Creation by steempytutorials

View this thread on: hive.blogpeakd.comecency.com
· @steempytutorials · (edited)
$16.46
Part 20: Plotting Account's Total Generated Post Rewards Since Creation
<center>![steem-python.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1515886103/kmzfcpvtzuwhvqhgpyjp.png)</center>

This tutorial is part of a series where different aspects of programming with `steem-python` are explained. Links to the other tutorials can be found in the curriculum section below. This part will focus on calculating the total rewards an account has generated with blog posts since its creation!

---

#### What will I learn

- How to create a dictionary with dates as keys
- How to save blog post rewards to a dictionary
- How to sum generated blog post rewards
- How to use `pyplot` to create a graph

#### Requirements

- Python3.6
- `steem-python`

#### Difficulty

- Intermediate

---

### Tutorial
If you find it easier to follow along this way you can get the entire code for this tutorial from [here](https://github.com/amosbastian/steempy-tutorials/blob/master/part_20/generated_rewards.py), where I have split everything up into the relevant sections.

#### Creating a dictionary of dates
First things first, we need to create a dictionary of dates from the account's creation until now, where each day is a key. As you might recall an account has a "created" attribute, so getting the account creation date and turning it into a `datetime` object is easy. Once we have this we can subtract it from today's date to get the total amount of days passed, like so

```python
account = "steempytutorials"
created = parse(Account(account)["created"]).date()
today = datetime.today().date()
days = today - created

>>> 32 days, 0:00:00
```
Once we have this we can simply iterate over all dates between the account's creation and today by adding the amount of days using `timedelta` to the account's creation date. This looks like this

```python
dates = {}

for day in range(days.days + 1):
    # Convert date to a string so it can be used as key
    dates[str(created + timedelta(days=day))] = 0
```

which results in our dictionary looking like this

```json
{
  "2017-12-30": 0,
  ...,
  "2018-01-31": 0
}
```

#### Iterating over all blog posts
We now have our dictionary, so we can start getting each blog post's total generated rewards. To do this we can reuse the code we used in part 18, as seen below

```python
while post_limit < Account(account)["post_count"]:
    print(post_limit, post_limit + 500)
    for post in steem.get_blog(account, post_limit, 500):
        post = Post(post["comment"])
        if post.is_main_post() and post["author"] == account:
            # COUNT TOTAL REWARD AND ADD TO DICTIONARY

    post_limit += 500
```

We want to replace the comment with some code that gets the post's total generated reward. If a post is less than 7 days old, then this reward will still be pending, but otherwise it has already been paid out to the author, curators and beneficaries (if applicable). So what we will do is simply check if an account still has pending rewards and use that as the payout, and if that's not the case, then we will add the author's payout with the curator's payout together and use that instead. Once we have this we obviously want to add this to our dictionary, so we also need to get the day the post was made. To do all this we can use the following code

```python
# Convert post creation date to string
post_date = str(post["created"].date())

# If pending payout then use this
payout = Amount(post["pending_payout_value"]).amount

# Otherwise sum author reward and curator reward
if payout == 0:
    payout = (Amount(post["total_payout_value"]).amount + 
        Amount(post["curator_payout_value"]).amount)
        
# Add this to the relevant key
dates[post_date] += payout
```

Printing our dictionary once again gives us the following updated dictionary

```json
{
  "2017-12-30": 0,
  "2017-12-31": 0,
  ...,
  "2018-01-30": 37.868,
  "2018-01-31": 3.843
}
```

#### Plotting the graph
Before we can plot this using `pyplot` there are a few things we need to do. First of all, to get the `x` values we need to convert the keys of the dictionary back to `datetime` objects and append them to a list. To do this we can use some list comprehension

```python
x = [datetime.strptime(date, "%Y-%m-%d").date() for date in dates.keys()]
```

For the `y` values we want the total sum of rewards up until that point in time. To do this we can iterate over the dictionary's values and for each index sum the relevant slice.

```python
y = [sum(list(dates.values())[0:i]) for i in range(len(dates.values()))]
```
This might look a bit complicated at first glance. Imagine it like this if it's a bit too difficult to understand

```
y = [sum(Post rewards day 1), sum(Post rewards day 1, Post rewards day 2), ...,  sum(Post rewards day 1, ..., Post rewards last day)]  
```

Alright, so now we have the `x` and `y` values all that's left is to plot them! But before we do that, let's also find out when the account generated its first reward (so we can show the date when this happened). We can simply calculate the index of when this happened and use this to show it as an `xtick` like so.

```python
def first_reward():
    for i, reward in enumerate(y):
        if reward > 0:
            return i

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# Set the xticks
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.xticks([x[0], x[first_reward() - 1], x[-1]], visible=True,
    rotation="horizontal")
```

Once we have that, all that's left is actually plotting the graph, which is made very easy with `pyplot`

```python
plt.plot(x, y)

# Always label your axes!
plt.xlabel("{} to {} for @{}".format(created, today, account))
plt.ylabel("Sum of post rewards generated")

# Add a nice grid show the plot
plt.grid()
plt.show()
```

which results in the following graph for @steempytutorials. 

<center>![steempytutorials_rewards.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1517432947/pjlffd8zm9wnpjsycv9l.png)
</center>

**Note:** this is not what the author has earned themselves, but what their posts have generated in total (a lot of other factors come in to play if you wanted to calculate this). Also **there is a bug if you have more than 500 posts** (or it could be intended behaviour), since `get_blog()` seems to repeat the most recent 500 posts despite setting a different `entry_id`.

#### Curriculum
##### Set up:
- [Part 0: How To Install Steem-python, The Official Steem Library For Python](https://utopian.io/utopian-io/@amosbastian/how-to-install-steem-python-the-official-steem-library-for-python)
- [Part 1: How To Configure The Steempy CLI Wallet And Upvote An Article With Steem-Python](https://utopian.io/utopian-io/@steempytutorials/part-1-how-to-configure-the-steempy-cli-wallet-and-upvote-an-article-with-steem-python)
##### Filtering
- [Part 2: How To Stream And Filter The Blockchain Using Steem-Python](https://utopian.io/utopian-io/@steempytutorials/part-2-how-to-stream-and-filter-the-blockchain-using-steem-python)
- [Part 6: How To Automatically Reply To Mentions Using Steem-Python](https://utopian.io/utopian-io/@steempytutorials/part-6-how-to-automatically-reply-to-mentions-using-steem-python)
##### Voting
- [Part 3: Creating A Dynamic Autovoter That Runs 24/7](https://utopian.io/utopian-io/@steempytutorials/part-3-creating-a-dynamic-upvote-bot-that-runs-24-7-first-weekly-challenge-3-steem-prize-pool)
- [Part 4: How To Follow A Voting Trail Using Steem-Python](https://utopian.io/utopian-io/@steempytutorials/part-4-how-to-follow-a-voting-trail-using-steem-python)
- [Part 8: How To Create Your Own Upvote Bot Using Steem-Python](https://utopian.io/utopian-io/@steempytutorials/part-8-how-to-create-your-own-upvote-bot-using-steem-python)
##### Posting
- [Part 5: Post An Article Directly To The Steem Blockchain And Automatically Buy Upvotes From Upvote Bots](https://utopian.io/utopian-io/@steempytutorials/part-5-post-an-article-directly-to-the-steem-blockchain-and-automatically-buy-upvotes-from-upvote-bots)
- [Part 7: How To Schedule Posts And Manually Upvote Posts For A Variable Voting Weight With Steem-Python](https://utopian.io/utopian-io/@steempytutorials/part-7-how-to-schedule-posts-and-manually-upvote-posts-for-a-variable-voting-weight-with-steem-python)
##### Constructing
- [Part 10: Use Urls To Retrieve Post Data And Construct A Dynamic Post With Steem-Python](https://utopian.io/utopian-io/@steempytutorials/part-10-use-urls-to-retrieve-post-data-and-construct-a-dynamic-post-with-steem-python)
##### Rewards
- [Part 9: How To Calculate A Post's Total Rewards Using Steem-Python](https://utopian.io/utopian-io/@steempytutorials/how-to-calculate-a-post-s-total-rewards-using-steem-python)
- [Part 12: How To Estimate Curation Rewards Using Steem-Python](https://utopian.io/utopian-io/@steempytutorials/part-12-how-to-estimate-curation-rewards)
- [Part 14: How To Estimate All Rewards In Last N Days Using Steem-Python](https://utopian.io/utopian-io/@steempytutorials/how-to-estimate-all-rewards-in-last-n-days-using-steem-python)
##### Transfers
- [Part 11: How To Build A List Of Transfers And Broadcast These In One Transaction With Steem-Python](https://utopian.io/utopian-io/@steempytutorials/part-11-how-to-build-a-list-of-transfers-and-broadcast-these-in-one-transaction-with-steem-python)
- [Part 13: Upvote Posts In Batches Based On Current Voting Power With Steem-Python](https://utopian.io/utopian-io/@steempytutorials/part-13-upvote-posts-in-batches-based-on-current-voting-power-with-steem-python)
##### Analysis
- [Part 15: How To Check If An Account Is Following Back And Retrieve Mutual Followers/Following Between Two Accounts](https://utopian.io/utopian-io/@steempytutorials/part-15-how-to-check-if-an-account-is-following-back-and-retrieve-mutual-followers-following-between-two-accounts)
- [Part 16: How To Analyse A User's Vote History In A Specific Time Period Using Steem-Python](https://steemit.com/utopian-io/@steempytutorials/part-16-how-to-analyse-a-user-s-vote-history-in-a-specific-time-period-using-steem-python)
- [Part 18: How To Analyse An Account's Resteemers Using Steem-Python](https://steemit.com/utopian-io/@steempytutorials/part-18-how-to-analyse-an-account-s-resteemers)
- [Part 19: Analysing The Steem Blockchain From A Custom Block Number For A Custom Block Count](http://utopian.io/utopian-io/@steempytutorials/part-19-analysing-the-steem-blockchain-for-a-custom-block-number-for-a-custom-block-count)
---

The code for this tutorial can be found on [GitHub](https://github.com/amosbastian/steempy-tutorials/tree/master/part_20)!

This tutorial was written by @amosbastian in conjunction with @juliank.

<br /><hr/><em>Posted on <a href="https://utopian.io/utopian-io/@steempytutorials/part-20-plotting-account-s-total-generated-post-rewards-since-creation">Utopian.io -  Rewarding Open Source Contributors</a></em><hr/>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , ,
properties (23)
authorsteempytutorials
permlinkpart-20-plotting-account-s-total-generated-post-rewards-since-creation
categoryutopian-io
json_metadata{"community":"utopian","app":"utopian/1.0.0","format":"markdown","repository":{"id":84843862,"name":"steem-python","full_name":"steemit/steem-python","html_url":"https://github.com/steemit/steem-python","fork":false,"owner":{"login":"steemit"}},"pullRequests":[],"platform":"github","type":"tutorials","tags":["utopian-io","steemdev","python","programming","tutorial"],"users":["steempytutorials","amosbastian","juliank"],"links":["https://github.com/amosbastian/steempy-tutorials/blob/master/part_20/generated_rewards.py","https://utopian.io/utopian-io/@amosbastian/how-to-install-steem-python-the-official-steem-library-for-python","https://utopian.io/utopian-io/@steempytutorials/part-1-how-to-configure-the-steempy-cli-wallet-and-upvote-an-article-with-steem-python","https://utopian.io/utopian-io/@steempytutorials/part-2-how-to-stream-and-filter-the-blockchain-using-steem-python","https://utopian.io/utopian-io/@steempytutorials/part-6-how-to-automatically-reply-to-mentions-using-steem-python","https://utopian.io/utopian-io/@steempytutorials/part-3-creating-a-dynamic-upvote-bot-that-runs-24-7-first-weekly-challenge-3-steem-prize-pool","https://utopian.io/utopian-io/@steempytutorials/part-4-how-to-follow-a-voting-trail-using-steem-python","https://utopian.io/utopian-io/@steempytutorials/part-8-how-to-create-your-own-upvote-bot-using-steem-python","https://utopian.io/utopian-io/@steempytutorials/part-5-post-an-article-directly-to-the-steem-blockchain-and-automatically-buy-upvotes-from-upvote-bots","https://utopian.io/utopian-io/@steempytutorials/part-7-how-to-schedule-posts-and-manually-upvote-posts-for-a-variable-voting-weight-with-steem-python","https://utopian.io/utopian-io/@steempytutorials/part-10-use-urls-to-retrieve-post-data-and-construct-a-dynamic-post-with-steem-python","https://utopian.io/utopian-io/@steempytutorials/how-to-calculate-a-post-s-total-rewards-using-steem-python","https://utopian.io/utopian-io/@steempytutorials/part-12-how-to-estimate-curation-rewards","https://utopian.io/utopian-io/@steempytutorials/how-to-estimate-all-rewards-in-last-n-days-using-steem-python","https://utopian.io/utopian-io/@steempytutorials/part-11-how-to-build-a-list-of-transfers-and-broadcast-these-in-one-transaction-with-steem-python","https://utopian.io/utopian-io/@steempytutorials/part-13-upvote-posts-in-batches-based-on-current-voting-power-with-steem-python","https://utopian.io/utopian-io/@steempytutorials/part-15-how-to-check-if-an-account-is-following-back-and-retrieve-mutual-followers-following-between-two-accounts","https://steemit.com/utopian-io/@steempytutorials/part-16-how-to-analyse-a-user-s-vote-history-in-a-specific-time-period-using-steem-python","https://steemit.com/utopian-io/@steempytutorials/part-18-how-to-analyse-an-account-s-resteemers","http://utopian.io/utopian-io/@steempytutorials/part-19-analysing-the-steem-blockchain-for-a-custom-block-number-for-a-custom-block-count","https://github.com/amosbastian/steempy-tutorials/tree/master/part_20","https://utopian.io/utopian-io/@steempytutorials/part-20-plotting-account-s-total-generated-post-rewards-since-creation"],"image":["https://res.cloudinary.com/hpiynhbhq/image/upload/v1515886103/kmzfcpvtzuwhvqhgpyjp.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1517432947/pjlffd8zm9wnpjsycv9l.png"],"moderator":{"account":"jestemkioskiem","time":"2018-02-01T15:46:59.808Z","reviewed":true,"pending":false,"flagged":false}}
created2018-01-31 21:15:45
last_update2018-02-01 15:47:09
depth0
children3
last_payout2018-02-07 21:15:45
cashout_time1969-12-31 23:59:59
total_payout_value12.904 HBD
curator_payout_value3.551 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length10,910
author_reputation31,094,047,689,691
root_title"Part 20: Plotting Account's Total Generated Post Rewards Since Creation"
beneficiaries
0.
accountutopian.pay
weight2,500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id33,951,913
net_rshares3,344,444,701,809
author_curate_reward""
vote details (27)
@jestemkioskiem ·
Thank you for the contribution. It has been approved.

You can contact us on [Discord](https://discord.gg/uTyJkNm).
**[[utopian-moderator]](https://utopian.io/moderators)**
properties (22)
authorjestemkioskiem
permlinkre-steempytutorials-part-20-plotting-account-s-total-generated-post-rewards-since-creation-20180201t145524913z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-02-01 15:55:24
last_update2018-02-01 15:55:24
depth1
children0
last_payout2018-02-08 15:55:24
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_length172
author_reputation41,292,066,961,817
root_title"Part 20: Plotting Account's Total Generated Post Rewards Since Creation"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id34,165,004
net_rshares0
@makerhacks ·
$0.03
You seem to read my mind with these tutorials! Thank you so much for putting them together :)

(@themarkymark and I were discussing how to work out the ROI of our efforts on Steemit - this will help a great deal!)
👍  ,
properties (23)
authormakerhacks
permlinkre-steempytutorials-part-20-plotting-account-s-total-generated-post-rewards-since-creation-20180131t214331162z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["themarkymark"],"app":"steemit/0.1"}
created2018-01-31 21:43:30
last_update2018-01-31 21:43:30
depth1
children0
last_payout2018-02-07 21:43:30
cashout_time1969-12-31 23:59:59
total_payout_value0.034 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length213
author_reputation156,251,640,481,040
root_title"Part 20: Plotting Account's Total Generated Post Rewards Since Creation"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id33,957,247
net_rshares5,991,540,955
author_curate_reward""
vote details (2)
@utopian-io ·
### Hey @steempytutorials I am @utopian-io. I have just upvoted you!
#### Achievements
- Seems like you contribute quite often. AMAZING!
#### Suggestions
- Contribute more often to get higher and higher rewards. I wish to see you often!
- Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!
#### Get Noticed!
- Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!
#### Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. <a href="https://discord.gg/zTrEMqB">Participate on Discord</a>. Lets GROW TOGETHER!
- <a href="https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1">Vote for my Witness With SteemConnect</a>
- <a href="https://v2.steemconnect.com/sign/account-witness-proxy?proxy=utopian-io&approve=1">Proxy vote to Utopian Witness with SteemConnect</a>
- Or vote/proxy on <a href="https://steemit.com/~witnesses">Steemit Witnesses</a>

[![mooncryption-utopian-witness-gif](https://steemitimages.com/DQmYPUuQRptAqNBCQRwQjKWAqWU3zJkL3RXVUtEKVury8up/mooncryption-s-utopian-io-witness-gif.gif)](https://steemit.com/~witnesses)

**Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x**
properties (22)
authorutopian-io
permlinkre-steempytutorials-part-20-plotting-account-s-total-generated-post-rewards-since-creation-20180202t060358224z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-02-02 06:03:57
last_update2018-02-02 06:03:57
depth1
children0
last_payout2018-02-09 06:03: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_length1,436
author_reputation152,955,367,999,756
root_title"Part 20: Plotting Account's Total Generated Post Rewards Since Creation"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id34,320,228
net_rshares0