GithubHelp home page GithubHelp logo

martinpyka / financial_life Goto Github PK

View Code? Open in Web Editor NEW
134.0 17.0 26.0 888 KB

A framework for analysing financial products in personalized contexts

License: Apache License 2.0

Python 97.47% HTML 2.47% Shell 0.06%
financial loan financial-products simulation financial-plans python

financial_life's Introduction

financial-life

A framework for analysing financial products in personalized contexts

Latest Release latest release

CHANGELOG.md

Description

financial_life is an opinionated framework written in Python that allows to simulate monetary flows between different types of accounts. These simulations allow a deeper understanding of financial plans and a better comparison of financial products (in particular loan conditions) for personal circumstances. With financial_life you can

  • analyse loan conditions and payment strategies
  • describe the properties of your financial plans with a few lines of code
  • create dynamic monetary flows between accounts for modeling more realistic scenarios
  • extend the code by controller functions (e.g. for modeling tax payments)

View documentation for a more detailed introduction.

Example

Say you want to model an account with regular income and payments to a loan

from financial_life.financing import accounts as a
from datetime import timedelta, datetime

# create a private bank account and a loan account
account = a.Bank_Account(amount = 1000, interest = 0.001, name = 'Main account')
loan = a.Loan(amount = 100000, interest = 0.01, name = 'House Credit')

# add these accounts to the simulation
simulation = a.Simulation(account, loan)

# describe monetary flows between accounts
simulation.add_regular('Income', account, 2000, interval = 'monthly')
simulation.add_regular(account, loan, lambda: min(1500, -loan.account), interval = 'monthly')

# simulate for ten years
simulation.simulate(delta = timedelta(days=365*10))

# plot the data
simulation.plt_summary()

# print reports summarized by years
print(account.report.yearly())
print(loan.report.yearly())

# analyze data
print("Interests on bank account: %.2f" % sum(account.report.yearly().interest))
print("Interests on loan account: %.2f" % sum(loan.report.yearly().interest))

The output will look like this:

Simple simulation in financial_life

Main account
Date          account     output     input    interest
----------  ---------  ---------  --------  ----------
31.12.2016    2000.32   -3000.00   4000.00        0.32
31.12.2017    8005.58  -18000.00  24000.00        5.26
31.12.2018   14016.85  -18000.00  24000.00       11.27
31.12.2019   20034.13  -18000.00  24000.00       17.28
31.12.2020   26057.42  -18000.00  24000.00       23.29
31.12.2021   32086.74  -18000.00  24000.00       29.32
31.12.2022   46271.00   -9853.30  24000.00       37.56
31.12.2023   70330.32       0.00  24000.00       59.32
31.12.2024   94413.68       0.00  24000.00       83.36
31.12.2025  118521.15       0.00  24000.00      107.47
01.10.2026  138521.15       0.00  20000.00        0.00
House Credit
Date          account    interest    payment
----------  ---------  ----------  ---------
31.12.2016  -97190.22     -190.22    3000.00
31.12.2017  -80064.23     -874.01   18000.00
31.12.2018  -62766.98     -702.75   18000.00
31.12.2019  -45296.76     -529.78   18000.00
31.12.2020  -27652.02     -355.26   18000.00
31.12.2021   -9830.65     -178.63   18000.00
31.12.2022       0.00      -22.65    9853.30
31.12.2023       0.00        0.00       0.00
31.12.2024       0.00        0.00       0.00
31.12.2025       0.00        0.00       0.00
Interests on bank account: 374.45
Interests on loan account: -2853.30

Now let's say, we put some money on a special savings account with better interests, because we want to purchase in two years a car. With financial_life, you just add the necessary changes to your model.

# create new account
savings = a.Bank_Account(amount = 5000, interest = 0.007, name = 'Savings')

# add it to the simulation (or create a new simulation with all three accounts)
simulation.add_account(savings)

# add regular payment to the savings-account
simulation.add_regular(account, savings, 500, interval = 'monthly')

# somewhere in the distant future we will make a payment to
# the vendor of a car
simulation.add_unique(savings, 'Vendor of a car', 10000, '17.03.2019')

The plot will now include the savings-account as well.

Simple simulation in financial_life

You can also export the simulation to HTML to explore your model in the browser:

from financial_life.reports import html

html.report(simulation, style="standard", output_dir = result_folder)

Simple simulation in financial_life

You can analyse the reports as pandas DataFrame as well and export it to excel:

import pandas as pd
from financial_life.reports import excel

account.report.as_df()    # Hello pandas
excel.report(simulation, filename='reports.xls')  # explore the results in excel

Here are more examples. financial_life supports:

  • dependencies between accounts, e.g. to model how the ownership of a property rises when the loan decreases
  • meta-data, e.g. for writing tax-calculations, which require additional knowledge about your payments
  • controller-functions for dynamic changes of the simulation properties during simulation

Installation

financial_life is available in version 0.9.2. It is written in Python 3.4 and has not been tested for Python 2.x.

To get a working environment, simply do

git clone https://github.com/MartinPyka/financial_life.git
cd financial_life
virtualenv venv
source venv/bin/activate
pip install -r requirements.txt
# test an example
python financial_life/examples/simple_examples.py

For installing the package:

git clone https://github.com/MartinPyka/financial_life.git
cd financial_life
python setup.py install

Or use pip

pip install financial_life

You can checkout the example with

python financial_life/examples/simple_examples.py

Why financial_life

financial_life was designed with the idea in mind that any line of code should contribute to the description of the problem you want to model. In spreadsheets, you would deal with a lot of auxiliary tables to accurately calculate the course of a loan influenced by incoming payments and generated interests. In financial_life, you just create your loan account with the given interests rate and you define the regular payments going into this loan account. That's it. Changes in the model and the exploration of different parameters within this model are therefore way easier to accomplish than in a spreadsheet-based simulation.

financial_life's People

Contributors

martinpyka avatar siecje avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

financial_life's Issues

Error with using add_unique() with loans

When adding a unique from loan to a dummy account:

simulation.add_unique(loan, 'Damages', 12000, date=datetime(2020,1,1))

I get the following error:

/home/masasin/.virtualenvs/financial_life/lib/python3.6/site-packages/financial_life/financing/accounts.py:706: UserWarning: Difference between current date and next date is 0 and not 1
  warnings.warn('Difference between current date and next date is %i and not 1' % delta)
Traceback (most recent call last):
  File "finsim.py", line 19, in <module>
    simulation.simulate(delta=timedelta(days=365*10))
  File "/home/masasin/.virtualenvs/financial_life/lib/python3.6/site-packages/financial_life/financing/accounts.py", line 509, in simulate
    self.make_transfer(payment)
  File "/home/masasin/.virtualenvs/financial_life/lib/python3.6/site-packages/financial_life/financing/accounts.py", line 462, in make_transfer
    meta = payment['meta']
TypeError: make_report() got an unexpected keyword argument 'date'

You can simulate the expected behaviour by doing:

simulation.add_unique('Damages', loan, -12000, date=datetime(2020,1,1))

edit: This doesn't do anything either if the starting loan amount is 0, but works when it is 0.01 or any other number.

Use CapWords for class names

It's the Python standard in PEP-8, and having classes with Cap_Words (e.g., Bank_Account) is confusing. Since the API is not finalized yet, do you think it's possible to change those to BankAccount etc, and maybe keep the old ones, but with a deprecation warning?

Error simulation.add_regular()

I get an error when I run the usage example in the readme.

Traceback (most recent call last):
  File "fin.py", line 12, in <module>
    simulation.add_regular('Income', account, 2000, interval = 'monthly')
  File "C:\Users\cody\Desktop\fin\venv\lib\site-packages\financial_life\financing\accounts.py", line 236, in add_regular
    date_start = validate.valid_date(date_start)
  File "C:\Users\cody\Desktop\fin\venv\lib\site-packages\financial_life\financing\validate.py", line 44, in valid_date
    return Bank_Date.fromtimestamp(date.timestamp())
OverflowError: timestamp out of range

Add data-field to transaction

Each transaction should have an optional data-field in which additional information about the transaction can be stored in a dictionary form. This would allow to create controllers that can operate on meta-information about transactions (e.g. for tax return calculations).

Add appreciation/depreciation rate for assets/properties

It would be useful to have an appreciation/depreciation rate for properties. This would allow a user to do thinks like add their car and car loan to a simulation as a depreciating asset, or add an appreciation factor to a property to make it easy to see LTV over time, if an asset is going to be underwater in the future, etc. This functionality could also be used to add inflation to simulations to produce outputs in inflation adjusted dollars.

Reports should be of type pandas.DataFrame

This will be the next feature that I plan to implement. Reports should be of type pandas.DataFrame, to leverage the data analysis tools available through pandas in this context.

SyntaxError: invalid syntax

  File "/usr/local/lib/python2.7/site-packages/financial_life/financing/accounts.py", line 103
    def __init__(self, *accounts, name = None, date = None, meta = None):
                                     ^
SyntaxError: invalid syntax

Cannot build html reports - jpg not supported.

Traceback:

Traceback (most recent call last):
  File "simple.py", line 135, in <module>
    example2()
  File "simple.py", line 81, in example2
    html.report(simulation, style="standard", output_dir = result_folder)
  File "/home/masasin/.virtualenvs/financial_life/lib/python3.6/site-packages/financial_life/reports/html.py", line 34, in report
    render_module.render(simulation, output_dir)
  File "/home/masasin/.virtualenvs/financial_life/lib/python3.6/site-packages/financial_life/reports/../templates/html/standard/render.py", line 35, in render
    img_data = plt.summary_img(*simulation.reports('yearly'), target = img_folder)
  File "/home/masasin/.virtualenvs/financial_life/lib/python3.6/site-packages/financial_life/financing/plotting.py", line 74, in summary_img
    fig.savefig(target + prefix + 'wealth.jpg', dpi = dpi)
  File "/home/masasin/.virtualenvs/financial_life/lib/python3.6/site-packages/matplotlib/figure.py", line 1573, in savefig
    self.canvas.print_figure(*args, **kwargs)
  File "/home/masasin/.virtualenvs/financial_life/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 2153, in print_figure
    canvas = self._get_output_canvas(format)
  File "/home/masasin/.virtualenvs/financial_life/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 2093, in _get_output_canvas
    '%s.' % (format, ', '.join(formats)))
ValueError: Format "jpg" is not supported.
Supported formats: eps, pdf, pgf, png, ps, raw, rgba, svg, svgz.     

Add predefined simulations to framework

Predefined and parametrized simulations would help to focus even more on certain questions that the user wants to answer with fl.

Example:
buying real estate for living and later on for renting
the simulation could setup all revelant accounts and could be parametric (e.g. number of years living in this property before renting, interests etc.)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.