<center></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>
</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/>