Ejemplo n.º 1
0
def insert_stock_trading_record(data: dict, stock_account: object):
    """Inserts a stock trading (i.e., buying or selling stocks) records."""
    from finance.models import Asset, Record
    if data['category1'].startswith('장내'):
        code_suffix = '.KS'
    elif data['category1'].startswith('코스닥'):
        code_suffix = '.KQ'
    else:
        code_suffix = ''
        raise ValueError(
            "code_suffix could not be determined with the category '{}'"
            ''.format(data['category1']))

    code = data['code'] + code_suffix

    asset = Asset.get_by_symbol(code)
    if asset is None:
        raise ValueError(
            "Asset object could not be retrived with code '{}'".format(code))

    return Record.create(
        created_at=data['date'],
        quantity=data['quantity'],
        asset=asset,
        account=stock_account,
    )
Ejemplo n.º 2
0
def insert_stock_trading_record(data: dict, stock_account: object):
    """Inserts a stock trading (i.e., buying or selling stocks) records."""
    from finance.models import Asset, Record
    if data['category1'].startswith('장내'):
        code_suffix = '.KS'
    elif data['category1'].startswith('코스닥'):
        code_suffix = '.KQ'
    else:
        code_suffix = ''
        raise ValueError(
            "code_suffix could not be determined with the category '{}'"
            ''.format(data['category1']))

    code = data['code'] + code_suffix

    asset = Asset.get_by_symbol(code)
    if asset is None:
        raise ValueError(
            "Asset object could not be retrived with code '{}'".format(code))

    return Record.create(
        created_at=data['date'],
        quantity=data['quantity'],
        asset=asset,
        account=stock_account,
    )
Ejemplo n.º 3
0
def import_miraeasset_foreign_records(
    fin: io.TextIOWrapper,
    account: Account,
):
    provider = Miraeasset()
    asset_krw = Asset.get_by_symbol('KRW')

    for r in provider.parse_foreign_transactions(fin):
        assert r.currency != 'KRW'
        # FIXME: Handle a case where asset cannot be found
        target_asset = Asset.get_by_symbol(r.currency)

        if r.category == '해외주매수':
            asset_stock = Asset.get_by_isin(r.code)
            make_double_record_transaction(
                r.synthesized_created_at,
                account,
                target_asset, -r.amount,
                asset_stock, r.quantity)
        elif r.category == '해외주매도':
            asset_stock = Asset.get_by_isin(r.code)
            make_double_record_transaction(
                r.synthesized_created_at,
                account,
                asset_stock, -r.quantity,
                target_asset, r.amount)
        elif r.category == '해외주배당금':
            make_single_record_transaction(
                r.synthesized_created_at,
                account, target_asset, r.amount)
        elif r.category == '환전매수':
            local_amount = int(r.raw_columns[6])  # amount in KRW
            make_double_record_transaction(
                r.synthesized_created_at,
                account,
                asset_krw, -local_amount,
                target_asset, r.amount)
        elif r.category == '환전매도':
            raise NotImplementedError
        elif r.category == '외화인지세':
            make_single_record_transaction(
                r.synthesized_created_at,
                account, target_asset, -r.amount)
        else:
            raise ValueError('Unknown record category: {0}'.format(r.category))
Ejemplo n.º 4
0
def import_stock_values(fin: io.TextIOWrapper, code: str, base_asset=None):
    """Import stock values."""
    asset = Asset.get_by_symbol(code)
    reader = csv.reader(
        fin, delimiter=',', quotechar='"', skipinitialspace=True)
    for date, open_, high, low, close_, volume, source in reader:
        try:
            yield AssetValue.create(
                evaluated_at=date, granularity=Granularity.day, asset=asset,
                base_asset=base_asset, open=open_, high=high, low=low,
                close=close_, volume=volume, source=source)
        except IntegrityError:
            log.warn('AssetValue for {0} on {1} already exist', code, date)
            db.session.rollback()
Ejemplo n.º 5
0
def test_import_miraeasset_foreign_records(
    asset_usd, asset_krw, account_stock, stock_asset_spy, stock_asset_amzn,
    stock_asset_nvda, stock_asset_amd, stock_asset_sbux
):
    with open('tests/samples/miraeasset_foreign.csv') as fin:
        import_miraeasset_foreign_records(fin, account_stock)

    balance = account_stock.balance()
    balance_sheet = [
        ('USD', -483.39),
        ('AMD', 22),
        ('SPY', 5),
        ('SBUX', 2),
        ('AMZN', 3),
        ('NVDA', 13),
    ]
    for symbol, amount in balance_sheet:
        asset = Asset.get_by_symbol(symbol)
        assert balance[asset] == Decimal(str(amount))
Ejemplo n.º 6
0
def test_import_miraeasset_foreign_records(asset_usd, asset_krw, account_stock,
                                           stock_asset_spy, stock_asset_amzn,
                                           stock_asset_nvda, stock_asset_amd,
                                           stock_asset_sbux):
    with open('tests/samples/miraeasset_foreign.csv') as fin:
        import_miraeasset_foreign_records(fin, account_stock)

    balance = account_stock.balance()
    balance_sheet = [
        ('USD', -483.39),
        ('AMD', 22),
        ('SPY', 5),
        ('SBUX', 2),
        ('AMZN', 3),
        ('NVDA', 13),
    ]
    for symbol, amount in balance_sheet:
        asset = Asset.get_by_symbol(symbol)
        assert balance[asset] == Decimal(str(amount))
Ejemplo n.º 7
0
def fetch_asset_values(code, start_time, end_time):
    try:
        asset = Asset.get_by_symbol(code)
    except AssetNotFoundException:
        log.info('Asset {0} does not exist. Creating an Asset record...', code)
        asset = Asset.create(name=code, code=code, type=AssetType.stock)

    rows = fetch_stock_values(code, start_time, end_time, Granularity.min)

    for date, open_, high, low, close_, volume, source in rows:
        insert_asset_value(asset, date, Granularity.min, open_, high, low,
                           close_, volume, source)

    try:
        db.session.commit()
    except (IntegrityError, InvalidRequestError):
        log.exception('Something went wrong')
        db.session.rollback()
    else:
        log.info('Asset values for {0} have been imported', code)
Ejemplo n.º 8
0
def import_stock_values(fin: io.TextIOWrapper, code: str, base_asset=None):
    """Import stock values."""
    asset = Asset.get_by_symbol(code)
    reader = csv.reader(fin,
                        delimiter=',',
                        quotechar='"',
                        skipinitialspace=True)
    for date, open_, high, low, close_, volume, source in reader:
        try:
            yield AssetValue.create(evaluated_at=date,
                                    granularity=Granularity.day,
                                    asset=asset,
                                    base_asset=base_asset,
                                    open=open_,
                                    high=high,
                                    low=low,
                                    close=close_,
                                    volume=volume,
                                    source=source)
        except IntegrityError:
            log.warn('AssetValue for {0} on {1} already exist', code, date)
            db.session.rollback()
Ejemplo n.º 9
0
def insert_stock_trading_record(data: dict, stock_account: object):
    """Inserts a stock trading (i.e., buying or selling stocks) records."""
    from finance.models import Asset, deposit

    if data["category1"].startswith("장내"):
        code_suffix = ".KS"
    elif data["category1"].startswith("코스닥"):
        code_suffix = ".KQ"
    else:
        code_suffix = ""
        raise ValueError(
            "code_suffix could not be determined with the category '{}'"
            "".format(data["category1"]))

    code = data["code"] + code_suffix

    asset = Asset.get_by_symbol(code)
    if asset is None:
        raise ValueError(
            "Asset object could not be retrived with code '{}'".format(code))

    return deposit(stock_account, asset, data["quantity"], data["date"])
Ejemplo n.º 10
0
def test_get_asset_by_symbol_non_existing(asset_sp500):
    with pytest.raises(AssetNotFoundException):
        Asset.get_by_symbol('non-exisiting')
Ejemplo n.º 11
0
def test_get_asset_by_symbol(stock_asset_ncsoft):
    asset = Asset.get_by_symbol('036570.KS')
    assert asset.description == 'NCsoft Corporation'
Ejemplo n.º 12
0
def test_get_asset_by_symbol_non_existing(asset_sp500):
    with pytest.raises(AssetNotFoundException):
        Asset.get_by_symbol('non-exisiting')
Ejemplo n.º 13
0
def test_get_asset_by_symbol(stock_asset_ncsoft):
    asset = Asset.get_by_symbol('036570.KS')
    assert asset.description == 'NCsoft Corporation'