Пример #1
0
def test_records(account_checking, asset_krw):
    with Transaction.create() as t:
        record = Record.create(
            created_at=parse_date('2016-03-14'), transaction=t,
            account=account_checking, asset=asset_krw,
            quantity=1000)

        # Make sure the record type has been set implictly
        assert RecordType.deposit == record.type

    with Transaction.create() as t:
        record = Record.create(
            created_at=parse_date('2016-03-14'), transaction=t,
            account=account_checking, asset=asset_krw,
            quantity=-2000)

        # Make sure the record type has been set implictly
        assert RecordType.withdraw == record.type

    with Transaction.create() as t:
        record = Record.create(
            created_at=parse_date('2016-03-14'), transaction=t,
            account=account_checking, asset=asset_krw,
            quantity=3000, type=RecordType.balance_adjustment)

        # Make sure the record type has been set explicitly
        assert RecordType.balance_adjustment == record.type
Пример #2
0
def test_records(account_checking, asset_krw):
    with Transaction.create() as t:
        record = Record.create(created_at=parse_date('2016-03-14'),
                               transaction=t,
                               account=account_checking,
                               asset=asset_krw,
                               quantity=1000)

        # Make sure the record type has been set implictly
        assert RecordType.deposit == record.type

    with Transaction.create() as t:
        record = Record.create(created_at=parse_date('2016-03-14'),
                               transaction=t,
                               account=account_checking,
                               asset=asset_krw,
                               quantity=-2000)

        # Make sure the record type has been set implictly
        assert RecordType.withdraw == record.type

    with Transaction.create() as t:
        record = Record.create(created_at=parse_date('2016-03-14'),
                               transaction=t,
                               account=account_checking,
                               asset=asset_krw,
                               quantity=3000,
                               type=RecordType.balance_adjustment)

        # Make sure the record type has been set explicitly
        assert RecordType.balance_adjustment == record.type
Пример #3
0
def import_8percent_data(parsed_data, account_checking, account_8p, asset_krw):
    from finance.models import Asset, AssetValue, Record, Transaction

    assert account_checking
    assert account_8p
    assert asset_krw

    asset_8p = Asset.create(name=parsed_data['name'])
    remaining_value = parsed_data['amount']
    started_at = parsed_data['started_at']

    with Transaction.create() as t:
        Record.create(
            created_at=started_at, transaction=t, account=account_checking,
            asset=asset_krw, quantity=-remaining_value)
        Record.create(
            created_at=started_at, transaction=t, account=account_8p,
            asset=asset_8p, quantity=1)
    AssetValue.create(
        evaluated_at=started_at, asset=asset_8p,
        target_asset=asset_krw, granularity='1day', close=remaining_value)

    for record in parsed_data['records']:
        date, principle, interest, tax, fees = record
        returned = principle + interest - (tax + fees)
        remaining_value -= principle
        with Transaction.create() as t:
            Record.create(
                created_at=date, transaction=t,
                account=account_checking, asset=asset_krw, quantity=returned)
        AssetValue.create(
            evaluated_at=date, asset=asset_8p,
            target_asset=asset_krw, granularity='1day', close=remaining_value)
Пример #4
0
def test_transaction():
    with Transaction.create() as t:
        assert t.state == TransactionState.initiated
    assert t.state == TransactionState.closed

    t = Transaction.create()
    assert t.state == TransactionState.initiated
    t.close(closed_at=datetime.utcnow())
    assert t.state == TransactionState.closed
Пример #5
0
def test_transaction():
    with Transaction.create() as t:
        assert t.state == TransactionState.initiated
    assert t.state == TransactionState.closed

    t = Transaction.create()
    assert t.state == TransactionState.initiated
    t.close(closed_at=datetime.utcnow())
    assert t.state == TransactionState.closed
Пример #6
0
def test_account_net_worth_1(account_checking, asset_krw):
    assert 0 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-01'), base_asset=asset_krw)
    assert 0 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-02'), base_asset=asset_krw)
    assert 0 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-03'), base_asset=asset_krw)
    assert 0 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-04'), base_asset=asset_krw)

    with Transaction.create() as t:
        Record.create(created_at=parse_date('2016-01-01'),
                      transaction=t,
                      account=account_checking,
                      asset=asset_krw,
                      quantity=1000)

    assert 1000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-01'), base_asset=asset_krw)
    assert 1000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-02'), base_asset=asset_krw)
    assert 1000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-03'), base_asset=asset_krw)
    assert 1000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-04'), base_asset=asset_krw)

    with Transaction.create() as t:
        Record.create(created_at=parse_date('2016-01-02'),
                      transaction=t,
                      account=account_checking,
                      asset=asset_krw,
                      quantity=2000)

    assert 1000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-01'), base_asset=asset_krw)
    assert 3000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-02'), base_asset=asset_krw)
    assert 3000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-03'), base_asset=asset_krw)
    assert 3000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-04'), base_asset=asset_krw)

    with Transaction.create() as t:
        Record.create(created_at=parse_date('2016-01-03'),
                      transaction=t,
                      account=account_checking,
                      asset=asset_krw,
                      quantity=-1500)

    assert 1000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-01'), base_asset=asset_krw)
    assert 3000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-02'), base_asset=asset_krw)
    assert 1500 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-03'), base_asset=asset_krw)
    assert 1500 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-04'), base_asset=asset_krw)
Пример #7
0
def test_portfolio(account_hf, asset_hf1, account_checking, asset_krw):
    portfolio = Portfolio()
    portfolio.base_asset = asset_krw
    portfolio.add_accounts(account_hf, account_checking)

    with Transaction.create() as t:
        Record.create(
            created_at=parse_date('2015-12-04'), transaction=t,
            account=account_checking, asset=asset_krw, quantity=500000)
        Record.create(
            created_at=parse_date('2015-12-04'), transaction=t,
            account=account_checking, asset=asset_krw, quantity=-500000)
        Record.create(
            created_at=parse_date('2015-12-04'), transaction=t,
            account=account_hf, asset=asset_hf1, quantity=1)

    # The net asset value shall not be available at this point
    with pytest.raises(AssetValueUnavailableException):
        net_worth = portfolio.net_worth(evaluated_at=parse_date('2015-12-04'),
                                        granularity=Granularity.day)

    # Initial asset value
    AssetValue.create(
        evaluated_at=parse_date('2015-12-04'), asset=asset_hf1,
        base_asset=asset_krw, granularity=Granularity.day, close=500000)

    net_worth = portfolio.net_worth(evaluated_at=parse_date('2015-12-04'),
                                    granularity=Granularity.day)
    assert 500000 == net_worth

    # 1st payment
    interest, tax, returned = 3923, 740, 30930
    with Transaction.create() as t:
        Record.create(
            created_at=parse_date('2016-01-08'), transaction=t,
            account=account_checking, asset=asset_krw, quantity=returned)
    # Remaining principle value after the 1st payment
    AssetValue.create(
        evaluated_at=parse_date('2016-01-08'), asset=asset_hf1,
        base_asset=asset_krw, granularity=Granularity.day, close=472253)

    net_worth = portfolio.net_worth(evaluated_at=parse_date('2016-01-08'),
                                    granularity=Granularity.day)
    assert 500000 + (interest - tax) == net_worth

    # 2nd payment
    with Transaction.create() as t:
        Record.create(
            created_at=parse_date('2016-02-05'), transaction=t,
            account=account_checking, asset=asset_krw, quantity=25016)
    # Remaining principle value after the 2nd payment
    AssetValue.create(
        evaluated_at=parse_date('2016-02-05'), asset=asset_hf1,
        base_asset=asset_krw, granularity=Granularity.day, close=450195)

    db.session.delete(portfolio)
    db.session.commit()
Пример #8
0
def test_account_net_worth_1(account_checking, asset_krw):
    assert 0 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-01'), base_asset=asset_krw)
    assert 0 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-02'), base_asset=asset_krw)
    assert 0 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-03'), base_asset=asset_krw)
    assert 0 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-04'), base_asset=asset_krw)

    with Transaction.create() as t:
        Record.create(
            created_at=parse_date('2016-01-01'), transaction=t,
            account=account_checking, asset=asset_krw, quantity=1000)

    assert 1000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-01'), base_asset=asset_krw)
    assert 1000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-02'), base_asset=asset_krw)
    assert 1000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-03'), base_asset=asset_krw)
    assert 1000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-04'), base_asset=asset_krw)

    with Transaction.create() as t:
        Record.create(
            created_at=parse_date('2016-01-02'), transaction=t,
            account=account_checking, asset=asset_krw, quantity=2000)

    assert 1000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-01'), base_asset=asset_krw)
    assert 3000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-02'), base_asset=asset_krw)
    assert 3000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-03'), base_asset=asset_krw)
    assert 3000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-04'), base_asset=asset_krw)

    with Transaction.create() as t:
        Record.create(
            created_at=parse_date('2016-01-03'), transaction=t,
            account=account_checking, asset=asset_krw, quantity=-1500)

    assert 1000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-01'), base_asset=asset_krw)
    assert 3000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-02'), base_asset=asset_krw)
    assert 1500 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-03'), base_asset=asset_krw)
    assert 1500 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-04'), base_asset=asset_krw)
Пример #9
0
def add_transaction(request, mid):
    if request.method == "POST":
        post_data = request.POST
        form = AddTransaction(post_data)
        month = Month.objects.get(pk=mid)
        if form.is_valid():
            data = form.cleaned_data
            score_source = Score.objects.get(
                pk=post_data.get('score_source', ''))
            data['score_source'] = score_source
            data['month'] = month
            score_goal_id = post_data.get('score_goal', '')
            if score_goal_id:
                score_goal = Score.objects.get(pk=score_goal_id)
                data['score_goal'] = str(score_goal.id)
                data['score_goal_name'] = score_goal.account.name
                transaction = Transaction(**data)
                transaction.save()
                score_source.remainder -= data['amount']
                score_source.save()
                score_goal.remainder += data['amount']
                score_goal.save()
                messages.success(request, u"Переказ успішно доданий!")
            elif post_data.get('planned_expense', ''):
                planned_expense = PlannedExpense.objects.get(
                    pk=post_data.get('planned_expense', ''))
                data['planned_expense'] = planned_expense
                transaction = Transaction(**data)
                transaction.save()
                change_accounts(transaction, planned_expense, month,
                                score_source, True)
                messages.success(request, u"Витрата успішно додана!")
    return HttpResponseRedirect(reverse("show_balance", kwargs={'mid': mid}))
Пример #10
0
def test_portfolio(account_hf, asset_hf1, account_checking, asset_krw):
    portfolio = Portfolio()
    portfolio.base_asset = asset_krw
    portfolio.add_accounts(account_hf, account_checking)

    deposit(account_checking, asset_krw, 500000, parse_date("2015-12-04"))

    with Transaction.create() as t:
        deposit(account_checking, asset_krw, -500000, parse_date("2015-12-04"),
                t)
        deposit(account_hf, asset_hf1, 1, parse_date("2015-12-04"), t)

    # The net asset value shall not be available at this point
    with pytest.raises(AssetValueUnavailableException):
        net_worth = portfolio.net_worth(evaluated_at=parse_date("2015-12-04"),
                                        granularity=Granularity.day)

    # Initial asset value
    AssetValue.create(
        evaluated_at=parse_date("2015-12-04"),
        asset=asset_hf1,
        base_asset=asset_krw,
        granularity=Granularity.day,
        close=500000,
    )

    net_worth = portfolio.net_worth(evaluated_at=parse_date("2015-12-04"),
                                    granularity=Granularity.day)
    assert 500000 == net_worth

    # 1st payment
    interest, tax, returned = 3923, 740, 30930
    deposit(account_checking, asset_krw, returned, parse_date("2016-01-08"))

    # Remaining principle value after the 1st payment
    AssetValue.create(
        evaluated_at=parse_date("2016-01-08"),
        asset=asset_hf1,
        base_asset=asset_krw,
        granularity=Granularity.day,
        close=472253,
    )

    net_worth = portfolio.net_worth(evaluated_at=parse_date("2016-01-08"),
                                    granularity=Granularity.day)
    assert 500000 + (interest - tax) == net_worth

    # 2nd payment
    deposit(account_checking, asset_krw, 25016, parse_date("2016-02-05"))
    # Remaining principle value after the 2nd payment
    AssetValue.create(
        evaluated_at=parse_date("2016-02-05"),
        asset=asset_hf1,
        base_asset=asset_krw,
        granularity=Granularity.day,
        close=450195,
    )

    db.session.delete(portfolio)
    db.session.commit()
Пример #11
0
def test_account_net_worth_2(account_checking, account_sp500, asset_krw, asset_sp500):
    AssetValue.create(
        evaluated_at=parse_date('2016-02-25'), asset=asset_sp500,
        base_asset=asset_krw, granularity=Granularity.day, close=921.77)
    AssetValue.create(
        evaluated_at=parse_date('2016-02-24'), asset=asset_sp500,
        base_asset=asset_krw, granularity=Granularity.day, close=932.00)
    AssetValue.create(
        evaluated_at=parse_date('2016-02-23'), asset=asset_sp500,
        base_asset=asset_krw, granularity=Granularity.day, close=921.06)
    AssetValue.create(
        evaluated_at=parse_date('2016-02-22'), asset=asset_sp500,
        base_asset=asset_krw, granularity=Granularity.day, close=921.76)

    with Transaction.create() as t:
        Record.create(
            created_at=parse_date('2016-02-25'), transaction=t,
            account=account_sp500, asset=asset_sp500,
            quantity=1000)
        Record.create(
            created_at=parse_date('2016-02-25'), transaction=t,
            account=account_checking, asset=asset_krw,
            quantity=-1000 * 921.77)

    assert 921770 == account_sp500.net_worth(
        evaluated_at=parse_date('2016-02-25'), base_asset=asset_krw)

    assert 921770 == account_sp500.net_worth(
        evaluated_at=parse_date('2016-03-01'), approximation=True,
        base_asset=asset_krw)
Пример #12
0
def test_account_net_worth_2(account_checking, account_sp500, asset_krw,
                             asset_sp500):
    AssetValue.create(evaluated_at=parse_date('2016-02-25'),
                      asset=asset_sp500,
                      base_asset=asset_krw,
                      granularity=Granularity.day,
                      close=921.77)
    AssetValue.create(evaluated_at=parse_date('2016-02-24'),
                      asset=asset_sp500,
                      base_asset=asset_krw,
                      granularity=Granularity.day,
                      close=932.00)
    AssetValue.create(evaluated_at=parse_date('2016-02-23'),
                      asset=asset_sp500,
                      base_asset=asset_krw,
                      granularity=Granularity.day,
                      close=921.06)
    AssetValue.create(evaluated_at=parse_date('2016-02-22'),
                      asset=asset_sp500,
                      base_asset=asset_krw,
                      granularity=Granularity.day,
                      close=921.76)

    with Transaction.create() as t:
        deposit(account_sp500, asset_sp500, 1000, parse_date('2016-02-25'), t)
        deposit(account_checking, asset_krw, -1000 * 921.77,
                parse_date('2016-02-25'), t)

    assert 921770 == account_sp500.net_worth(
        evaluated_at=parse_date('2016-02-25'), base_asset=asset_krw)

    assert 921770 == account_sp500.net_worth(
        evaluated_at=parse_date('2016-03-01'),
        approximation=True,
        base_asset=asset_krw)
Пример #13
0
def import_sp500_records():
    """Import S&P500 fund sample data. Expects a tab seprated value document.
    """
    app = create_app(__name__)
    app.app_context().push()

    account_checking = Account.get(id=1001)
    account_sp500 = Account.get(id=7001)
    asset_krw = Asset.query.filter_by(name='KRW').first()
    asset_sp500 = Asset.query.filter_by(name='KB S&P500').first()

    # Expected number of columns
    expected_col_count = 6

    with open('sample-data/sp500.csv') as fin:
        # Skip the first row (headers)
        headers = next(fin)
        col_count = len(headers.split())
        if col_count != expected_col_count:
            raise Exception(
                'Expected number of columns = {}, '
                'actual number of columns = {}'.format(
                    expected_col_count, col_count))

        for line in fin:
            cols = line.split('\t')
            if len(cols) != expected_col_count:
                continue
            date = parse_date(cols[0], '%Y.%m.%d')
            _type = cols[1]
            quantity_krw, quantity_sp500 = \
                [int(extract_numbers(v)) for v in cols[3:5]]

            log.info(', '.join([c.strip() for c in cols]))

            if not (_type == '일반입금' or _type == '일반신규'):
                log.info('Record type \'{}\' will be ignored', _type)
                continue

            with Transaction.create() as t:
                # NOTE: The actual deposit date and the buying date generally
                # differ by a few days. Need to figure out how to parse this
                # properly from the raw data.
                try:
                    Record.create(
                        created_at=date, account=account_checking,
                        asset=asset_krw, quantity=-quantity_krw,
                        transaction=t)
                except IntegrityError:
                    log.warn('Identical record exists')
                    db.session.rollback()

                try:
                    Record.create(
                        created_at=date, account=account_sp500,
                        asset=asset_sp500, quantity=quantity_sp500,
                        transaction=t)
                except IntegrityError:
                    log.warn('Identical record exists')
                    db.session.rollback()
Пример #14
0
def make_double_record_transaction(created_at, account, asset_from,
                                   quantity_from, asset_to, quantity_to):
    """Creates a double record transaction (e.g., a buy order of stocks)"""
    with Transaction.create() as t:
        record1 = deposit(account, asset_from, quantity_from, created_at, t)
        record2 = deposit(account, asset_to, quantity_to, created_at, t)
    return (record1, record2)
Пример #15
0
def test_account_net_worth_1(account_checking, asset_krw):
    assert 0 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-01'), base_asset=asset_krw)
    assert 0 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-02'), base_asset=asset_krw)
    assert 0 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-03'), base_asset=asset_krw)
    assert 0 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-04'), base_asset=asset_krw)

    with Transaction.create() as t:
        deposit(account_checking, asset_krw, 1000, parse_date('2016-01-01'), t)

    assert 1000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-01'), base_asset=asset_krw)
    assert 1000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-02'), base_asset=asset_krw)
    assert 1000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-03'), base_asset=asset_krw)
    assert 1000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-04'), base_asset=asset_krw)

    with Transaction.create() as t:
        deposit(account_checking, asset_krw, 2000, parse_date('2016-01-02'), t)

    assert 1000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-01'), base_asset=asset_krw)
    assert 3000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-02'), base_asset=asset_krw)
    assert 3000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-03'), base_asset=asset_krw)
    assert 3000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-04'), base_asset=asset_krw)

    with Transaction.create() as t:
        deposit(account_checking, asset_krw, -1500, parse_date('2016-01-03'),
                t)

    assert 1000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-01'), base_asset=asset_krw)
    assert 3000 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-02'), base_asset=asset_krw)
    assert 1500 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-03'), base_asset=asset_krw)
    assert 1500 == account_checking.net_worth(
        evaluated_at=parse_date('2016-01-04'), base_asset=asset_krw)
Пример #16
0
def import_csv(filename, account):
    '''
    '''
    # CSVs come in many formats, find a matching profile
    for profile in CsvImportProfile.objects.all().order_by('order'):
        if profile.match(filename):
            logging.info("Found matching CSV profile: %s", profile)
            break
    else:
        raise ValueError, "No profiles matched the file"
    
    with open(filename, 'rb') as csv_file:
        transactions = parse_csv(csv_file, profile.get_fieldnames(), 
                                 dayfirst=profile.date_day_first,
                                 skip_rows=profile.data_start_row)
    logging.info("%d CSV transactions found in file %s", len(transactions), filename)
    for t in transactions:
        # split payee string into parts
        try:
            trans_type, payee = match_transaction_type(t['payee'])
        except ValueError:
            logging.warning("Transaction type cannot be determined: %s", t['payee'])
            trans_type = None
            payee = t['payee']

        # create and save Transactions in DB            
        new_transaction = Transaction(
            account = account,
            name = payee, #TODO: populate or remove as we don't need a name?!
            date = t['date'],
            transaction_type = trans_type,
            payee = payee,
            ##paid_on = paid_on_dt,
            ##import_string = t['import_string'], # DictReader doesn't give us the original line
        )
        new_transaction.save()
            
        t_part = TransactionPart(
            transaction = new_transaction,
            amount = '%.2f' % t['amount'],
            category = match_category(payee),
        )
        t_part.save()
        logging.debug("Imported %s - %s", new_transaction, t_part)
    
    return len(transactions)
Пример #17
0
def import_sp500_records():
    """Import S&P500 fund sample data. Expects a tab seprated value document.
    """
    app = create_app(__name__)
    app.app_context().push()

    account_checking = Account.get(id=1001)
    account_sp500 = Account.get(id=7001)
    asset_krw = Asset.query.filter_by(name="KRW").first()
    asset_sp500 = Asset.query.filter_by(name="KB S&P500").first()

    # Expected number of columns
    expected_col_count = 6

    with open("sample-data/sp500.csv") as fin:
        # Skip the first row (headers)
        headers = next(fin)
        col_count = len(headers.split())
        if col_count != expected_col_count:
            raise Exception("Expected number of columns = {}, "
                            "actual number of columns = {}".format(
                                expected_col_count, col_count))

        for line in fin:
            cols = line.split("\t")
            if len(cols) != expected_col_count:
                continue
            date = parse_date(cols[0], "%Y.%m.%d")
            _type = cols[1]
            quantity_krw, quantity_sp500 = [
                int(extract_numbers(v)) for v in cols[3:5]
            ]

            log.info(", ".join([c.strip() for c in cols]))

            if not (_type == "일반입금" or _type == "일반신규"):
                log.info("Record type '{}' will be ignored", _type)
                continue

            with Transaction.create() as t:
                # NOTE: The actual deposit date and the buying date generally
                # differ by a few days. Need to figure out how to parse this
                # properly from the raw data.
                try:
                    deposit(account_checking, asset_krw, -quantity_krw, date,
                            t)
                except IntegrityError:
                    log.warn("Identical record exists")
                    db.session.rollback()

                try:
                    deposit(account_sp500, asset_sp500, quantity_sp500, date,
                            t)
                except IntegrityError:
                    log.warn("Identical record exists")
                    db.session.rollback()
Пример #18
0
def import_8percent_data(parsed_data, account_checking, account_8p, asset_krw):
    from finance.models import Asset, AssetValue, Record, Transaction

    assert account_checking
    assert account_8p
    assert asset_krw

    asset_8p = Asset.create(name=parsed_data['name'])
    remaining_value = parsed_data['amount']
    started_at = parsed_data['started_at']

    with Transaction.create() as t:
        Record.create(created_at=started_at,
                      transaction=t,
                      account=account_checking,
                      asset=asset_krw,
                      quantity=-remaining_value)
        Record.create(created_at=started_at,
                      transaction=t,
                      account=account_8p,
                      asset=asset_8p,
                      quantity=1)
    AssetValue.create(evaluated_at=started_at,
                      asset=asset_8p,
                      target_asset=asset_krw,
                      granularity='1day',
                      close=remaining_value)

    for record in parsed_data['records']:
        date, principle, interest, tax, fees = record
        returned = principle + interest - (tax + fees)
        remaining_value -= principle
        with Transaction.create() as t:
            Record.create(created_at=date,
                          transaction=t,
                          account=account_checking,
                          asset=asset_krw,
                          quantity=returned)
        AssetValue.create(evaluated_at=date,
                          asset=asset_8p,
                          target_asset=asset_krw,
                          granularity='1day',
                          close=remaining_value)
Пример #19
0
def test_records(account_checking, asset_krw):
    with Transaction.create() as t:
        record = deposit(account_checking, asset_krw, 1000,
                         parse_date('2016-03-14'), t)

        # Make sure the record type has been set implictly
        assert RecordType.deposit == record.type

    with Transaction.create() as t:
        record = deposit(account_checking, asset_krw, -2000,
                         parse_date('2016-03-14'), t)

        # Make sure the record type has been set implictly
        assert RecordType.withdraw == record.type

    with Transaction.create() as t:
        record = balance_adjustment(account_checking, asset_krw, 3000,
                                    parse_date('2016-03-14'), t)

        # Make sure the record type has been set explicitly
        assert RecordType.balance_adjustment == record.type
Пример #20
0
def saving_transfer(request, sid, action):
    saving = Saving.objects.get(pk=sid)
    if request.method == "POST":
        amount = request.POST.get('amount', '')
        transaction_data = {}
        if action == 'add':
            saving.amount += int(amount)
            transaction_data['amount'] = int(amount)
            transaction_data[
                'detail'] = u"Зарахування коштів на збереження {} по рахунку {}".format(
                    saving.saving_total.title, saving.account.name)
        elif action == 'remove':
            saving.amount -= int(amount)
            transaction_data['amount'] = -int(amount)
            transaction_data[
                'detail'] = u"Зняття коштів зі збереження {} по рахунку {}".format(
                    saving.saving_total.title, saving.account.name)
        saving.save()
        transaction_data['model'] = saving.__class__.__name__
        transaction_data['model_id'] = saving.id
        transaction = Transaction(**transaction_data)
        transaction.save()
        if action == 'add':
            messages.success(
                request,
                u"Кошти на {} на рахунок {} успішно зараховано".format(
                    saving.saving_total.title, saving.account.name))
        if action == 'remove':
            messages.error(
                request,
                u"Кошти зі збереження {} на рахунку {} успішно знято".format(
                    saving.saving_total.title, saving.account.name))
        return HttpResponseRedirect(reverse("savings_list"))
    elif request.method == "GET":
        return render(request, 'finance/saving_change.html', {
            'action': action,
            'saving': saving
        })
Пример #21
0
def update_salary():
    total = 0
    valid_clerk = Clerk.objects.filter(is_employee=True)

    for clerk in valid_clerk:
        total = total + clerk.salary
    company = get_dollarial_company()
    company_credit = company.get_credit("R")
    sum_all = 0
    salary_objects = []
    for clerk in valid_clerk:
        salary_object = Transaction(owner=clerk.user,
                                    amount=clerk.salary,
                                    currency='R',
                                    wage=0,
                                    status='A')
        payment_object = Transaction(owner=get_dollarial_user(),
                                     amount=-clerk.salary,
                                     currency='R',
                                     wage=0,
                                     status='A')
        salary_objects.append([salary_object, payment_object])
        sum_all += clerk.salary
    if sum_all > company_credit:
        send_email_to_user(
            "Low Credit", "*****@*****.**", ADMIN_EMAIL,
            "Your Credit is not enough to pay the salaries. Your Credit is " +
            str(company_credit) + " and total salaries is " + str(total))
        raise Exception("Not enough credit to create salaries")

    else:
        for x, y in salary_objects:
            x.save()
            y.save()
        send_email_to_user(
            "Salary paid", "*****@*****.**", ADMIN_EMAIL,
            " Clerks Salary Paid. Current credit: " +
            str(company_credit - sum_all))
Пример #22
0
def make_double_record_transaction(
    created_at, account, asset_from, quantity_from, asset_to, quantity_to
):
    """Creates a double record transaction (e.g., a buy order of stocks)"""
    with Transaction.create() as t:
        record1 = Record.create(
            transaction=t,
            account_id=account.id,
            asset_id=asset_from.id,
            created_at=created_at,
            quantity=quantity_from,
        )
        record2 = Record.create(
            transaction=t,
            account_id=account.id,
            asset_id=asset_to.id,
            created_at=created_at,
            quantity=quantity_to,
        )
    return (record1, record2)
Пример #23
0
# test database query with dummy data

from finance.models import Transaction
import random
from decimal import Decimal
from finance.models import Currency, Category

data_list: list = []
currencies = list(Currency.objects.all())
categories = list(Category.objects.all())

for i in range(1, 100000):
    data_tx = Transaction(amount=random.randrange(Decimal(i), Decimal(100000)), currency=random.choice(currencies), description="", category=random.choice(categories))
    data_list.append(data_tx)

# append data
Transaction.bulk_create(data_list)
Пример #24
0
    def create_transaction(self, account, date):
        num_transactions = random.randint(3, 5)
        for i in range(num_transactions):
            dt = self.get_datetime(date)
            t = Transaction(account=account)
            t.guid = uuid.uuid4().hex
            t.uid = uuid.uuid4().hex
            t.date = date
            t.created_at = timezone.make_aware(dt)
            t.updated_at = timezone.make_aware(dt)
            t.transacted_at = timezone.make_aware(dt)
            t.posted_at = timezone.make_aware(dt)
            t.amount = self.generate_amount()
            t.is_expense = True
            t.category = self.get_category()
            t.description = self.get_description()
            t.save()

            dt_str = dt.strftime('%Y-%m-%d %H:%M:%S')
            with freeze_time(dt_str):
                self.make_transfers(dt)
Пример #25
0
def import_qif(filename, account):
    """
    """
    with open(filename, 'rb') as qif_file:
        transactions = parse_qif(qif_file)
    logging.info("%d QIF transactions found in file %s", len(transactions), filename)
    for t in transactions:
        try:
            trans_type, payee = match_transaction_type(t['payee'])
        except ValueError:
            logging.warning("Transaction type cannot be determined: %s", t['payee'])
            trans_type = None
            payee = t['payee']

        # create and save Transactions in DB            
        new_transaction = Transaction(
            account = account,
            name = payee, #TODO: populate or remove as we don't need a name?!
            date = t['date'],
            transaction_type = trans_type,
            payee = payee,
            ##paid_on = paid_on_dt,
            import_string = t['import_string'],
        )  
        new_transaction.save()
        
        if t.get('amount_in_split'):
            part_list = []
            for n, amount in t['amount_in_split']:
                # create and save Transactions in DB
                if t.get('category_in_split'):
                    # assumed category_in_split has same number of items as amount
                    split_category = _get_category(t['category_in_split'][n])
                else:
                    split_category = match_category(payee)
                    
                t_part = TransactionPart(
                    transaction = new_transaction,
                    amount = '%.2f' % amount,
                    category = split_category,
                    description  = '', #TODO: iterate over t['memo'] field if available
                )
                t_part.save() #TODO: Required again after?
                part_list.append(t_part)
            logging.debug("Imported %s - %s", new_transaction, part_list)
                    
        else:
            # create a single transactionamount
            if t.get('category'):
                # Category from QIF takes priority if available
                category = _get_category(category_name)
            else:
                category = match_category(payee)
            t_part = TransactionPart(
                transaction = new_transaction,
                amount = '%.2f' % t['amount'],
                description = t.get('memo', ''),
                category = category,
            )
            t_part.save() #TODO: Required again after?
            logging.debug("Imported %s - %s", new_transaction, t_part)
    return len(transactions)
Пример #26
0
def test_portfolio(account_hf, asset_hf1, account_checking, asset_krw):
    portfolio = Portfolio()
    portfolio.base_asset = asset_krw
    portfolio.add_accounts(account_hf, account_checking)

    with Transaction.create() as t:
        Record.create(created_at=parse_date('2015-12-04'),
                      transaction=t,
                      account=account_checking,
                      asset=asset_krw,
                      quantity=500000)
        Record.create(created_at=parse_date('2015-12-04'),
                      transaction=t,
                      account=account_checking,
                      asset=asset_krw,
                      quantity=-500000)
        Record.create(created_at=parse_date('2015-12-04'),
                      transaction=t,
                      account=account_hf,
                      asset=asset_hf1,
                      quantity=1)

    # The net asset value shall not be available at this point
    with pytest.raises(AssetValueUnavailableException):
        net_worth = portfolio.net_worth(evaluated_at=parse_date('2015-12-04'),
                                        granularity=Granularity.day)

    # Initial asset value
    AssetValue.create(evaluated_at=parse_date('2015-12-04'),
                      asset=asset_hf1,
                      base_asset=asset_krw,
                      granularity=Granularity.day,
                      close=500000)

    net_worth = portfolio.net_worth(evaluated_at=parse_date('2015-12-04'),
                                    granularity=Granularity.day)
    assert 500000 == net_worth

    # 1st payment
    interest, tax, returned = 3923, 740, 30930
    with Transaction.create() as t:
        Record.create(created_at=parse_date('2016-01-08'),
                      transaction=t,
                      account=account_checking,
                      asset=asset_krw,
                      quantity=returned)
    # Remaining principle value after the 1st payment
    AssetValue.create(evaluated_at=parse_date('2016-01-08'),
                      asset=asset_hf1,
                      base_asset=asset_krw,
                      granularity=Granularity.day,
                      close=472253)

    net_worth = portfolio.net_worth(evaluated_at=parse_date('2016-01-08'),
                                    granularity=Granularity.day)
    assert 500000 + (interest - tax) == net_worth

    # 2nd payment
    with Transaction.create() as t:
        Record.create(created_at=parse_date('2016-02-05'),
                      transaction=t,
                      account=account_checking,
                      asset=asset_krw,
                      quantity=25016)
    # Remaining principle value after the 2nd payment
    AssetValue.create(evaluated_at=parse_date('2016-02-05'),
                      asset=asset_hf1,
                      base_asset=asset_krw,
                      granularity=Granularity.day,
                      close=450195)

    db.session.delete(portfolio)
    db.session.commit()
Пример #27
0
 def __create_transactions():
     user_k = User.objects.get(username="******")
     user_s = User.objects.get(username="******")
     transaction1 = Transaction(owner=user_k, amount="300", currency="D")
     transaction1.save()
     transaction2 = Transaction(owner=user_k, amount="30", currency="E")
     transaction2.save()
     transaction3 = Transaction(owner=user_k, amount="30000", currency="R")
     transaction3.save()
     transaction4 = Transaction(owner=user_s, amount="40000", currency="R")
     transaction4.save()
Пример #28
0
 def __create_transactions():
     user_k = User.objects.get(username="******")
     transaction1 = Transaction(owner=user_k, amount="300", currency="D")
     transaction1.save()
Пример #29
0
 def __create_transactions():
     user = User.objects.get(username="******")
     transaction1 = Transaction(owner=user, amount="300", currency="D")
     transaction1.save()
     transaction2 = Transaction(owner=user, amount="30", currency="E")
     transaction2.save()
     transaction3 = Transaction(owner=user, amount="30000", currency="R")
     transaction3.save()