def get_prices_and_save(self, tx_coll): """ create Gnucash prices, load and save to the Gnucash file's PriceDB :param tx_coll: InvestmentRecord object: transactions to use to extract Gnucash prices :return: message """ print_info('get_prices_and_save()', MAGENTA) gncu = GncUtilities() msg = TEST self.price_db.begin_edit() print_info("self.price_db.begin_edit()", MAGENTA) try: for plan_type in tx_coll.plans: print_info("\n\nPlan type = {}".format(plan_type)) for tx in tx_coll.plans[plan_type]: base = pow(10, len(tx[CENTS])) int_price = int(tx[DOLLARS] + tx[CENTS]) val = GncNumeric(int_price, base) ast_parent_path = copy.copy(ACCT_PATHS[ASSET]) ast_parent_path.append(plan_type) if plan_type != PL_OPEN: if tx_coll.get_owner() == UNKNOWN: raise Exception("PROBLEM!! Trying to process plan type '{}' but NO Owner information found" " in Tx Collection!!".format(plan_type)) ast_parent_path.append(ACCT_PATHS[tx_coll.get_owner()]) print_info("ast_parent_path = {}".format(str(ast_parent_path)), BLUE) asset_parent = gncu.account_from_path(self.root, ast_parent_path) # get the asset account name name_key = tx[FUND_CMPY].split(' ')[0] print_info("name_key = {}".format(name_key), YELLOW) if name_key in FUND_NAME_CODE.keys(): name_code = FUND_NAME_CODE[name_key] # special case if name_code == ATL: asset_acct_name = ATL_O59 else: asset_acct_name = name_code + " " + tx[FUND_CODE] else: raise Exception("Could NOT find name key {}!".format(name_key)) print_info("asset_acct_name = {}".format(asset_acct_name), BLUE) # special location for Trust Asset account if asset_acct_name == TRUST_AST_ACCT: asset_parent = self.root.lookup_by_name(TRUST) print_info("asset_parent = {}".format(asset_parent.GetName()), BLUE) # get the asset account asset_acct = asset_parent.lookup_by_name(asset_acct_name) if asset_acct is None: # just skip updating cash-holding funds if str(val) == '100000/10000': continue else: raise Exception( "Could NOT find acct '{}' under parent '{}'".format(asset_acct_name, asset_parent.GetName())) print_info("Adding: {}[{}] @ ${}".format(asset_acct_name, tx_coll.get_date_str(), val), GREEN) pr = GncPrice(self.book) pr.begin_edit() pr.set_time64(tx_coll.get_date()) comm = asset_acct.GetCommodity() print_info("Commodity = {}:{}".format(comm.get_namespace(), comm.get_printname()), YELLOW) pr.set_commodity(comm) pr.set_currency(self.currency) pr.set_value(val) pr.set_source_string("user:price") pr.set_typestr('last') pr.commit_edit() if self.prod: print_info("PROD: Add Price to DB.\n", GREEN) self.price_db.add_price(pr) else: print_info("PROD: ABANDON Prices!\n", RED) if self.prod: msg = "PROD: COMMIT Price DB edits and Save session." print_info("PROD: COMMIT Price DB edits and Save session.", GREEN) self.price_db.commit_edit() # only ONE session save for the entire run self.session.save() self.session.end() self.session.destroy() except Exception as e: msg = "get_prices_and_save() EXCEPTION!! '{}'".format(repr(e)) print_error(msg) if "session" in locals() and self.session is not None: self.session.end() self.session.destroy() raise return msg
''' import datetime import gnucash.gnucash_core_c from gnucash.function_class import ClassFromFunctions from gnucash import Session, GncPrice, GncNumeric def create_price(self, book): price_instance = gnucash.gnucash_core_c.gnc_price_create(book.get_instance()) ClassFromFunctions.__init__(self, instance=price_instance) GncPrice.__init__ = create_price if __name__ == '__main__': import tempfile with tempfile.NamedTemporaryFile(suffix='.gnucash', delete=False) as fd: print fd.name s = Session(fd.name, is_new=True) commod_tab = s.book.get_table() currency = commod_tab.lookup('ISO4217', 'USD') p = GncPrice(s.book) p.set_time(datetime.datetime.now()) p.set_commodity(currency) p.set_currency(commod_tab.lookup('ISO4217', 'EUR')) p.set_value(GncNumeric(123)) s.book.get_price_db().add_price(p) s.save() s.end()
import gnucash.gnucash_core_c from gnucash.function_class import ClassFromFunctions from gnucash import Session, GncPrice, GncNumeric def create_price(self, book=None, instance=None): if instance: price_instance = instance else: price_instance = gnucash.gnucash_core_c.gnc_price_create(book.get_instance()) ClassFromFunctions.__init__(self, instance=price_instance) GncPrice.__init__ = create_price if __name__ == '__main__': import tempfile with tempfile.NamedTemporaryFile(suffix='.gnucash', delete=False) as fd: print fd.name s = Session(fd.name, is_new=True) commod_tab = s.book.get_table() currency = commod_tab.lookup('ISO4217', 'USD') p = GncPrice(s.book) p.set_time(datetime.datetime.now()) p.set_commodity(currency) p.set_currency(commod_tab.lookup('ISO4217', 'EUR')) p.set_value(GncNumeric(123)) s.book.get_price_db().add_price(p) s.save() s.end()
# purge existing quotes logging.info("Purging quotes for %s in %s...", symbol, ns) # get existing quotes from the database p = pdb.get_prices(stock, cur) for i in range(0, len(p)): pdb.remove_price(p[i]) # add new quotes logging.info("Adding quotes for %s in %s...", symbol, ns) q = quotes[symbol] cnt = 0 for (date, price) in q: # import pdb; pdb.set_trace(); p = GncPrice(book) # new GncPrice object p.set_time(date) p.set_commodity(stock) p.set_currency(cur) p.set_value(floatToGncNumeric(price)) p.set_typestr("last") p.set_source("user:price-editor") # almost true! pdb.add_price(p) cnt = cnt + 1 logging.info("Ok. Added %i quotes for %s.", cnt, symbol) # clean up if not args.dryrun:
def create_gnc_price_txs(self, mtx:dict, ast_parent:Account, rev_acct:Account): """ Create and load Gnucash prices to the Gnucash PriceDB :param mtx: InvestmentRecord transaction :param ast_parent: Asset parent account :param rev_acct: Revenue account :return: nil """ self.logger.print_info('create_gnc_price_txs()', BLUE) conv_date = dt.strptime(mtx[DATE], "%d-%b-%Y") pr_date = dt(conv_date.year, conv_date.month, conv_date.day) datestring = pr_date.strftime("%Y-%m-%d") fund_name = mtx[FUND] if fund_name in MONEY_MKT_FUNDS: return int_price = int(mtx[PRICE].replace('.', '').replace('$', '')) val = GncNumeric(int_price, 10000) self.logger.print_info("Adding: {}[{}] @ ${}".format(fund_name, datestring, val)) pr1 = GncPrice(self.book) pr1.begin_edit() pr1.set_time64(pr_date) asset_acct, rev_acct = self.get_accounts(ast_parent, fund_name, rev_acct) comm = asset_acct.GetCommodity() self.logger.print_info("Commodity = {}:{}".format(comm.get_namespace(), comm.get_printname())) pr1.set_commodity(comm) pr1.set_currency(self.currency) pr1.set_value(val) pr1.set_source_string("user:price") pr1.set_typestr('nav') pr1.commit_edit() if self.mode == PROD: self.logger.print_info("Mode = {}: Add Price to DB.".format(self.mode), GREEN) self.price_db.add_price(pr1) else: self.logger.print_info("Mode = {}: ABANDON Prices!\n".format(self.mode), RED)
def create_gnc_prices(self, tx1, tx2): """ create and load Gnucash prices to the Gnucash PriceDB :param tx1: first transaction :param tx2: matching transaction, if exists :return: nil """ print_info('create_gnc_prices()', MAGENTA) pr_date = dt(tx1[TRADE_YR], tx1[TRADE_MTH], tx1[TRADE_DAY]) datestring = pr_date.strftime("%Y-%m-%d") int_price = int((tx1[GROSS] * 100) / (tx1[UNITS] / 10000)) val = GncNumeric(int_price, 10000) print_info("Adding: {}[{}] @ ${}".format(tx1[ACCT].GetName(), datestring, val)) pr1 = GncPrice(self.book) pr1.begin_edit() pr1.set_time64(pr_date) comm = tx1[ACCT].GetCommodity() print_info("Commodity = {}:{}".format(comm.get_namespace(), comm.get_printname())) pr1.set_commodity(comm) pr1.set_currency(self.curr) pr1.set_value(val) pr1.set_source_string("user:price") pr1.set_typestr('nav') pr1.commit_edit() if tx1[SWITCH]: # get the price for the paired Tx int_price = int((tx2[GROSS] * 100) / (tx2[UNITS] / 10000)) val = GncNumeric(int_price, 10000) print_info("Adding: {}[{}] @ ${}".format(tx2[ACCT].GetName(), datestring, val)) pr2 = GncPrice(self.book) pr2.begin_edit() pr2.set_time64(pr_date) comm = tx2[ACCT].GetCommodity() print_info("Commodity = {}:{}".format(comm.get_namespace(), comm.get_printname())) pr2.set_commodity(comm) pr2.set_currency(self.curr) pr2.set_value(val) pr2.set_source_string("user:price") pr2.set_typestr('nav') pr2.commit_edit() if self.mode == PROD: print_info("Mode = {}: Add Price1 to DB.".format(self.mode), GREEN) self.price_db.add_price(pr1) if tx1[SWITCH]: print_info("Mode = {}: Add Price2 to DB.".format(self.mode), GREEN) self.price_db.add_price(pr2) else: print_info("Mode = {}: ABANDON Prices!\n".format(self.mode), RED)