In [ ]:
import collections
import datetime
import time
import pandas as pd

from dateutil import rrule
from dateutil.parser import parse
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

from beancount.core import data
from beancount.ops import holdings
from beancount import loader
from beancount.reports import holdings_reports

plt.style.use('ggplot')

In [ ]:
# Load beancount file

filename = '/home/alex/finance/money.beancount'
entries, errors, options_map = loader.load_file(filename)

In [ ]:
#for entry in entries:
#    if isinstance(entry, data.Transaction):
#        dtstart = entry.date
#        break

# Manually set start date, avoids None results
dtstart = datetime.date(2015, 1, 1)

In [ ]:
net_worths_dict = collections.defaultdict(list)
index = 0
current_entries = []
dtend = datetime.date.today()
#period = rrule.rrule(rrule.WEEKLY, byweekday=rrule.FR, dtstart=dtstart, until=dtend)
period = rrule.rrule(rrule.MONTHLY, bymonthday=1, dtstart=dtstart, until=dtend)

In [ ]:
for dtime in period:
    date = dtime.date()

    # Append new entries until the given date.
    while True:
        entry = entries[index]
        if entry.date >= date:
            break
        current_entries.append(entry)
        index += 1

    # Get the list of holdings.
    raw_holdings_list, price_map = holdings_reports.get_assets_holdings(current_entries,
                                                                        options_map)

    # Convert the currencies.
    for currency in options_map['operating_currency']:
        holdings_list = holdings.convert_to_currency(price_map,
                                                     currency,
                                                     raw_holdings_list)

        holdings_list = holdings.aggregate_holdings_by(
            holdings_list, lambda holding: holding.cost_currency)

        holdings_list = [holding
                         for holding in holdings_list
                         if holding.currency and holding.cost_currency]

        # If after conversion there are no valid holdings, skip the currency
        # altogether.
        if not holdings_list:
            continue

        net_worths_dict[currency].append((date, holdings_list[0].market_value))

In [ ]:
xs, ys = zip(*net_worths_dict['GBP'])
plt.plot(xs, ys)
plt.show()

In [ ]:
#Extract data for c3 text for wiki

dates = ['x']
for value in xs:
    dates.append(value.strftime('%Y-%m-%d'))

values = ['Net Worth']
for amount in ys:
    if amount is None:
        amount = 0
    values.append(str(round(float(amount))))

In [ ]:
# Build text for dokuwiki

columns = "[{}, {}]".format(dates, values)
c3graphs = r"""
<c3>
data: {x: 'x', 
           columns:""" + columns + r"""
       },
    axis: {x: {
            type: 'timeseries',
            tick: {
                format: '%Y-%m-%d'
            }
        },
        y : {
             label: {
          text: 'GBP',
          position: 'outer-middle'
        }
      }
    }
</c3>
"""

print(c3graphs)

In [ ]:
# Data for spreadsheet
d = {'Date': xs, 'Networth': ys}
df = pd.DataFrame(data=d)
# format
df['Date'] = pd.to_datetime(df['Date'])
df['Networth'] = pd.to_numeric(df['Networth'])
df = df.round(0)
df

In [ ]:
#save to csv
df.to_csv('/home/alex/finance/networth.csv')