def get_cash_balance_as_of(at_date: dt.datetime = None) -> Position: """ method to get the cash balance from transactions at a certain date :param at_date: datetime :return: Position object """ if at_date is None: at_date = dt.datetime.today() transactions = mongo.find_documents( database_name='transactions', collection_name='transactions', projection={ '_id': 0, 'net_cashflow': 1 }, **{'transaction_date': { '$lte': at_date }}) transactions = [ list(transaction.values())[0] for transaction in transactions ] cash_balance = Series(transactions).sum() return Position(**{'asset_type': 'CASH', 'quantity': cash_balance})
def eps(self, annual_period: bool = False, eps_date: dt.datetime = None): period = 'annual' if annual_period else 'interim' if eps_date: query = { 'ric': self.ric, 'report_elem': 'Net Income', 'period': period, 'date': eps_date } else: query = { 'ric': self.ric, 'report_elem': 'Net Income', 'period': period } net_income = mongo.find_documents(database_name='financials', collection_name='income', sort=[('date', -1)], **query) net_income = net_income.__next__()['value'] * 1e6 outs_shares = int(self._instrument_details['instr']['nbShare']) eps = net_income / outs_shares return eps
def check_quotes(): quotes = list( mongo.find_documents('quotes', 'equities', **{"time": { '$gt': dt.datetime.today() }})) if len(quotes) > 0: # delete in mongo: mongo.mongo_client.quotes.equities.delete_many( {"time": { '$gt': dt.datetime.today() }}) quotes = list( mongo.find_documents('quotes', 'equities', **{"time": { '$gt': dt.datetime.today() }})) assert len(quotes) == 0
def get_income_statement_elements(ric, period, date=None): query_filter = {'ric': ric, 'period': period} if date: query_filter.update({'date': date}) income_statement_elems = mongo.find_documents(database_name='fundamentals', collection_name='income', **query_filter) return income_statement_elems
def get_balance_sheet_elements(ric, period, date=None): query_filter = {'ric': ric, 'period': period} if date: query_filter.update({'date': date}) balance_sheet_elems = mongo.find_documents(database_name='fundamentals', collection_name='balance_sheet', **query_filter) return balance_sheet_elems
def _compute_portfolio_navs(self) -> bool: """ method to compute the portfolio net asset values :return: bool """ asset_values = mongo.find_documents(database_name='net_asset_values', collection_name='net_asset_values', projection={'_id': 0}) df_assets = DataFrame(asset_values).set_index('date') df_assets['navs'] = df_assets['assets'] / df_assets['shares'] self._portfolio_navs = df_assets['navs'] return True
def get_last_price_in_mongo(isin): try: result = mongo.find_documents('quotes', 'equities', sort=[('time', -1)], projection={'_id': 0}, limit=1, **{'isin': isin})[0] price_date = result.get('time') result = result.get('price') logger.log.info(f'price for {isin} on date {price_date.year}-{price_date.month}-{price_date.day} : ' f'{result}') except IndexError: logger.log.warning(f'Could not find any price in mongo for {isin}') result = None return result
def _compute_positions_pnl(self) -> bool: """ Compute and store PnL from equity positions :return: True """ positions_pnl = {} for position in self._positions: if position.asset_type is AssetType.EQUITY: isin = position.isin transactions = list( mongo.find_documents( 'transactions', 'transactions', projection={"_id": 0}, sort=[('transaction_date', 1)], **{ 'isin': isin, 'transaction_type': { "$in": ['BUY', 'SELL', 'STOCK SPLIT'] } })) cumulative_positions = [] cum_position = 0 for trade in transactions: cum_position += trade['quantity'] cumulative_positions.append(cum_position) buy_transactions = [] for i in range(len(transactions) - 1, -1, -1): if cumulative_positions[i] == 0: break else: if transactions[i]['transaction_type'] in [ 'BUY', 'STOCK SPLIT' ]: buy_transactions.append(transactions[i]) sum_quantity = sum(trade['quantity'] for trade in buy_transactions) weighted_average_price = sum( trade['quantity'] * trade['price'] for trade in buy_transactions if trade['price'] is not None) / sum_quantity positions_pnl[isin] = self._stocks_prices[ isin] / weighted_average_price - 1 self._positions_pnl = positions_pnl return True
def get_equity_positions_as_of( at_date: dt.datetime = None) -> List[Position]: """ method to get equity positions at a certain date :param at_date: datetime :return: list of equity position objects """ if at_date is None: at_date = dt.datetime.today() transactions_quantities = mongo.find_documents( database_name='transactions', collection_name='transactions', projection={ '_id': 0, 'isin': 1, 'quantity': 1, 'mic': 1 }, **{ 'transaction_date': { '$lte': at_date }, 'isin': { '$ne': None } }) transactions_quantities = [ transactions for transactions in transactions_quantities ] if transactions_quantities: df = DataFrame(transactions_quantities).groupby(['isin', 'mic']).sum() positions = df[df['quantity'] != 0.0] positions['asset_type'] = 'EQUITY' positions.reset_index(inplace=True) result = [Position(**pos) for pos in positions.to_dict('records')] else: result = [] return result
import pandas as pd import datetime as dt from pynvestor.source import mongo from pynvestor.source.portfolio import Portfolio navs = list( mongo.find_documents('net_asset_values', 'net_asset_values', {'_id': 0}, sort=[("date", -1)])) last_date = navs[0]['date'] today = dt.datetime.today() # dates to update dates_to_update = pd.date_range(last_date, today, freq='7D') portfolios = [Portfolio(date).save_portfolio_nav() for date in dates_to_update]