Пример #1
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()
Пример #2
0
def test_create_model():
    Account.create(institution='Chase', number='1234')

    # IntegrityError is raised due to the unique constraint
    with pytest.raises(IntegrityError):
        Account.create(institution='Chase', number='1234')

    assert not Account.create(
        institution='Chase', number='1234', ignore_if_exists=True)
Пример #3
0
def create_accounts():
    for client in User.objects.all():
        if get_or_create_clients_group() in client.groups.all():
            accounts_count = random.randint(5, 10)
            for i in range(accounts_count):
                is_heavy_account = simple_event(10)
                money_range = random.randint(3000, 10000) if is_heavy_account else \
                    random.randint(300, 3000)
                Account.create(True, client, money_range)
Пример #4
0
def test_create_model():
    Account.create(institution='Chase', number='1234')

    # IntegrityError is raised due to the unique constraint
    with pytest.raises(IntegrityError):
        Account.create(institution='Chase', number='1234')

    assert not Account.create(institution='Chase', number='1234',
                              ignore_if_exists=True)
Пример #5
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()
Пример #6
0
def create_account(type_: AccountType, institution: str, number: str, user):
    return Account.create(type=type_,
                          name='Test account',
                          institution=institution,
                          number=number,
                          user=user,
                          ignore_if_exists=True)
Пример #7
0
def account_stock(request, db):
    account = Account.create(type=AccountType.investment,
                             institution='Miraeasset',
                             number='ACCOUNT1',
                             name='미래에셋대우 1')
    request.addfinalizer(partial(teardown, db=db, record=account))
    return account
Пример #8
0
    def add_event(
        self,
        account: models.Account,
        amount: decimal.Decimal,
        executed_at: datetime.datetime,
        event_type: models.EventType,
        position: Optional[models.Position] = None,
        withheld_taxes: Optional[decimal.Decimal] = None,
    ) -> Tuple[models.AccountEvent, bool]:

        if (event_type == models.EventType.DEPOSIT
                or event_type == models.EventType.DIVIDEND):
            assert amount > 0
        if event_type == models.EventType.WITHDRAWAL:
            assert amount < 0

        event, created = models.AccountEvent.objects.get_or_create(
            account=account,
            amount=amount,
            executed_at=executed_at,
            event_type=event_type,
            position=position,
            withheld_taxes=withheld_taxes or 0,
        )
        if created:
            balance_change = amount
            if withheld_taxes:
                balance_change -= withheld_taxes

            if event_type == models.EventType.DIVIDEND and position:
                position_currency = position.asset.currency
                account_currency = account.currency
                if position_currency != account_currency:
                    exchange_rate = prices.get_closest_exchange_rate(
                        date=executed_at.date(),
                        from_currency=position_currency,
                        to_currency=account_currency,
                    )
                    if exchange_rate is None:
                        raise ValueError(
                            f"Can't convert between currencies: "
                            f"{position_currency} and {account_currency}")
                    balance_change *= exchange_rate.value

            account.balance += balance_change
        account.save()
        return event, created
Пример #9
0
    def add_crypto_income_event(
        self,
        account: models.Account,
        symbol: str,
        executed_at: datetime.datetime,
        quantity: decimal.Decimal,
        price: decimal.Decimal,
        local_value: decimal.Decimal,
        value_in_account_currency: decimal.Decimal,
        event_type: models.EventType,
    ) -> Tuple[models.AccountEvent, bool]:

        (
            transaction,
            _,
        ) = self.add_transaction_crypto_asset(
            account,
            symbol,
            executed_at,
            quantity,
            price,
            # Local value.
            local_value,
            value_in_account_currency,
            value_in_account_currency,
        )

        position = transaction.position

        event, created = models.AccountEvent.objects.get_or_create(
            account=account,
            amount=-value_in_account_currency,
            executed_at=executed_at,
            event_type=event_type,
            position=position,
            transaction=transaction,
            withheld_taxes=0,
        )

        if created:
            account.balance += -value_in_account_currency
        account.save()

        return event, created
Пример #10
0
def add_account(request):
    if request.method == "POST":
        form = AddAccount(request.POST)
        if form.is_valid():
            data = {}
            data['name'] = form.cleaned_data['name']
            data['kind'] = form.cleaned_data['kind']
            account = Account(**data)
            account.save()
            savings = SavingTotal.objects.all()
            for saving in savings:
                data = {}
                data['saving_total'] = saving
                data['account'] = account
                new_saving = Saving(**data)
                new_saving.save()
            messages.success(request,
                             u"Рахунок %s успішно доданий" % account.name)
    url = reverse("home") + "?list=accounts"
    return HttpResponseRedirect(url)
Пример #11
0
def import_miraeasset_foreign_data(filename, account_institution,
                                   account_number):
    """Imports a CSV file exported in 해외거래내역 (9465)."""
    from finance.importers import import_miraeasset_foreign_records

    app = create_app(__name__)
    with app.app_context():
        account = Account.get_by_number(account_institution, account_number)

        with open(filename) as fin:
            import_miraeasset_foreign_records(fin, account)
Пример #12
0
def import_miraeasset_foreign_data(
    filename, account_institution, account_number
):
    """Imports a CSV file exported in 해외거래내역 (9465)."""
    from finance.importers import import_miraeasset_foreign_records

    app = create_app(__name__)
    with app.app_context():
        account = Account.get_by_number(account_institution, account_number)

        with open(filename) as fin:
            import_miraeasset_foreign_records(fin, account)
Пример #13
0
def addAccount(request, token):
    user = Token.getUser(int(token))
    if not user:
        return Response(status=status.HTTP_401_UNAUTHORIZED)

    try:
        total = int(request.POST['total'])
    except KeyError:
        return Response(status=status.HTTP_400_BAD_REQUEST)

    try:
        number = int(request.POST['number'])
    except KeyError:
        return Response(status=status.HTTP_400_BAD_REQUEST)

    try:
        name = int(request.POST['name'])
    except KeyError:
        return Response(status=status.HTTP_400_BAD_REQUEST)

    account = Account.create(total, name, user, number)
    serializer = AccountSerializer(account)
    return Response(serializer.data, status=status.HTTP_200_OK)
Пример #14
0
def account_hf(request, db):
    account = Account.create(type='virtual', name='어니스트펀드')
    request.addfinalizer(partial(teardown, db=db, record=account))
    return account
Пример #15
0
def account_checking(request, db):
    account = Account.create(type='checking', name='Shinhan Checking')
    request.addfinalizer(partial(teardown, db=db, record=account))
    return account
Пример #16
0
def account_checking(request, db):
    account = Account.create(type="checking", name="신한은행 입출금")
    request.addfinalizer(partial(teardown, db=db, record=account))
    return account
Пример #17
0
def account_stock(request, db):
    account = Account.create(type='investment', name='신한 주식')
    request.addfinalizer(partial(teardown, db=db, record=account))
    return account
Пример #18
0
def account_savings(request, db):
    account = Account.create(type='savings', name='신한은행 적금')
    request.addfinalizer(partial(teardown, db=db, record=account))
    return account
Пример #19
0
def account_8p(request, db):
    account = Account.create(type="virtual", name="8퍼센트")
    request.addfinalizer(partial(teardown, db=db, record=account))
    return account
Пример #20
0
    def create_account(self, member, account_type):
        """
        account_type: debit/debt
        """
        if account_type == 'debit':
            name = 'Debit {}'.format(member.name)
            acc_type = Account.CHECKING
            balance = random.randint(300, 2000)
        else:
            name = 'Credit {}'.format(member.name)
            acc_type = Account.LOAN
            balance = -random.randint(50000, 100000)

        a = Account(member=member)
        a.guid = uuid.uuid4().hex
        a.uid = uuid.uuid4().hex
        a.name = name
        a.type = acc_type
        a.updated_at = timezone.now()
        a.balance = balance
        a.available_balance = a.balance
        a.save()
Пример #21
0
def account_sp500(request, db):
    account = Account.create(type='investment', name='S&P500 Fund')
    request.addfinalizer(partial(teardown, db=db, record=account))
    return account
Пример #22
0
def account_savings(request, db):
    account = Account.create(type='savings', name='신한은행 적금')
    request.addfinalizer(partial(teardown, db=db, record=account))
    return account
Пример #23
0
def create_account(type_: AccountType, institution: str, number: str, user):
    return Account.create(
        type=type_, name='Test account', institution=institution,
        number=number, user=user, ignore_if_exists=True)
Пример #24
0
def account_stock(request, db):
    account = Account.create(
        type=AccountType.investment, institution='Miraeasset',
        number='ACCOUNT1', name='미래에셋대우 1')
    request.addfinalizer(partial(teardown, db=db, record=account))
    return account