def stock_assets(): with open('tests/samples/stocks.csv') as fin: reader = csv.reader(fin, delimiter=',') for row in reader: isin, code, name = row if isin.startswith('#'): continue Asset.create(type=AssetType.stock, isin=isin, code=code, name=name)
def stock_assets(): with open('tests/samples/stocks.csv') as fin: reader = csv.reader(fin, delimiter=',') for row in reader: isin, code, name = row if isin.startswith('#'): continue Asset.create( type=AssetType.stock, isin=isin, code=code, name=name)
def asset_stock_ncsoft(request, db): asset = Asset.create(type='stock', name='NCsoft Corporation', code='036570.KS', description='NCsoft Corporation') request.addfinalizer(partial(teardown, db=db, record=asset)) return asset
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, )
def asset_sp500(request, db): asset = Asset.create(type='security', name='KB Star S&P500', description='', data={'code': 'KR5223941018'}) request.addfinalizer(partial(teardown, db=db, record=asset)) return asset
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)
def asset_stock_nvda(request, db): asset = Asset.create(type='stock', name='NVDA', code='NVDA', description='NVIDIA Corporation') request.addfinalizer(partial(teardown, db=db, record=asset)) return asset
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))
def insert_asset(row, data=None): """Parses a comma separated values to fill in an Asset object. (type, name, description) :param row: comma separated values """ from finance.models import Asset type, name, description = [x.strip() for x in row.split(',')] return Asset.create( type=type, name=name, description=description, data=data)
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)
def insert_asset(row, data=None): """Parses a comma separated values to fill in an Asset object. (type, name, description) :param row: comma separated values """ from finance.models import Asset type, name, description = [x.strip() for x in row.split(',')] return Asset.create(type=type, name=name, description=description, data=data)
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()
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))
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))
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)
def insert_stock_assets(): """NOTE: This is a temporary workaround. All stock informaion shall be fetched automatically on the fly. """ rows = [ ('036570.KS', 'NCsoft Corporation'), ('145210.KS', 'SAEHWA IMC'), ('069080.KQ', 'Webzen'), ('053800.KQ', 'Ahnlab Inc.'), ('017670.KS', 'SK Telecom Co. Ltd.'), ('005380.KS', 'Hyundai Motor Company'), ('056080.KQ', 'Yujin Robot Co., Ltd.'), ('069500.KS', 'KODEX 200'), ('009830.KS', '한화케미칼'), ] for code, description in rows: log.info('Inserting {} ({})...', code, description) yield Asset.create(type='stock', code=code, description=description, ignore_if_exists=True)
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"])
def insert_stock_assets(): """NOTE: This is a temporary workaround. All stock informaion shall be fetched automatically on the fly. """ rows = [ ("036570.KS", "NCsoft Corporation"), ("145210.KS", "SAEHWA IMC"), ("069080.KQ", "Webzen"), ("053800.KQ", "Ahnlab Inc."), ("017670.KS", "SK Telecom Co. Ltd."), ("005380.KS", "Hyundai Motor Company"), ("056080.KQ", "Yujin Robot Co., Ltd."), ("069500.KS", "KODEX 200"), ("009830.KS", "한화케미칼"), ] for code, description in rows: log.info("Inserting {} ({})...", code, description) yield Asset.create(type="stock", code=code, description=description, ignore_if_exists=True)
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()
def test_insert_stock_record(db, account_stock, account_checking): data = { "date": parse_date("2016-06-30"), "sequence": 1, "category1": "장내매수", "category2": "매수", "code": "005380", "name": "현대차", "unit_price": 136000, "quantity": 10, "subtotal": 1360000, "interest": 0, "fees": 200, "late_fees": 0, "channel": "", "final_amount": 1670200, } asset = Asset.create(type="stock", code="005380.KS", description="현대차") record = insert_stock_record(data, account_stock, account_checking) # TODO: Automate this process db.session.delete(record) db.session.delete(asset) db.session.commit()
def test_insert_stock_record(db, account_stock, account_checking): data = { 'date': parse_date('2016-06-30'), 'sequence': 1, 'category1': '장내매수', 'category2': '매수', 'code': '005380', 'name': '현대차', 'unit_price': 136000, 'quantity': 10, 'subtotal': 1360000, 'interest': 0, 'fees': 200, 'late_fees': 0, 'channel': '', 'final_amount': 1670200, } asset = Asset.create(type='stock', code='005380.KS', description='현대차') record = insert_stock_record(data, account_stock, account_checking) # TODO: Automate this process db.session.delete(record) db.session.delete(asset) db.session.commit()
def asset_krw(request, db): asset = Asset.create( type='currency', name='KRW', description='Korean Won') request.addfinalizer(partial(teardown, db=db, record=asset)) return asset
def asset_hf1(request, db): asset = Asset.create( type='bond', name='포트폴리오 투자상품 1호') request.addfinalizer(partial(teardown, db=db, record=asset)) return asset
def create_asset(type_: AssetType, code: str, description: str): return Asset.create( type=type_, code=code, description=description, ignore_if_exists=True)
def test_get_asset_by_symbol(stock_asset_ncsoft): asset = Asset.get_by_symbol('036570.KS') assert asset.description == 'NCsoft Corporation'
def test_get_asset_by_isin(stock_asset_nvda): asset = Asset.get_by_isin('US67066G1040') assert asset.code == 'NVDA'
def test_get_asset_by_isin_non_existing(stock_asset_nvda): with pytest.raises(AssetNotFoundException): Asset.get_by_isin('non-exisiting')
def test_get_asset_by_symbol_non_existing(asset_sp500): with pytest.raises(AssetNotFoundException): Asset.get_by_symbol('non-exisiting')
def asset_sp500(request, db): asset = Asset.create( type='security', name='S&P 500', description='') request.addfinalizer(partial(teardown, db=db, record=asset)) return asset
def asset_usd(request, db): asset = Asset.create(type='currency', name='USD', description='United States Dollar') request.addfinalizer(partial(teardown, db=db, record=asset)) return asset
def create_asset(type_: AssetType, code: str, description: str): return Asset.create(type=type_, code=code, description=description, ignore_if_exists=True)
def test_get_asset_by_isin(stock_asset_nvda): asset = Asset.get_by_isin("US67066G1040") assert asset.code == "NVDA"