def insert_or_update(session, asks, bids, exchange, symbol, ob_datetime=None): if ob_datetime: # Example: '2018-12-13T19:49:42.000Z' ob_datetime = dateutil.parser.parse(ob_datetime, ignoretz=True) if not is_datetime_acceptable(ob_datetime, 60): # TODO: to avoid log spam, uncomment this only when you want to debug wrong datetimes # logging.warning(f'{exchange} {symbol} outdated datetime: {ob_datetime}') ob_datetime = datetime.datetime.now() else: ob_datetime = datetime.datetime.now() base = utils.get_currency(symbol, 1).upper() quote = utils.get_currency(symbol, 2).upper() _insert_or_update(session, asks, exchange, base, quote, 'ask', ob_datetime) _insert_or_update(session, bids, exchange, base, quote, 'bid', ob_datetime) session.commit()
def send_sms(): print(request.data) req_dict = request.form amt, credit, currency, card, ac, typ = parseSentence( req_dict["sms_message"], get_currency()) relevant = True personal_account = True credit_category = False if (credit == 'credit'): credit_category = True if (card == '9999'): personal_account = False data = { "relevant": relevant, "expense": amt, "type": typ, "currency": currency, "credit_category": credit_category, "personal_account": personal_account } return jsonify(data)
import os import time import numpy as np url = 'https://investir.lesechos.fr/traders/forex/' if __name__ == '__main__': #Create dump file if not created (not tracked by git) if not os.path.exists('../../data/'): os.makedirs('../../data/') finename = '../../data/forex.csv' soup, now = utils.make_the_soup(url) header, data = utils.get_currency(soup, now) with open(finename, 'wb') as f: np.savetxt(f, data, header=header) try: while True: soup, now = utils.make_the_soup(url) header, data = utils.get_currency(soup, now) utils.dump_data(f, data) print('Forex currency data loaded at ', now.hour, ':', now.minute, ':', now.second) time.sleep(180) except KeyboardInterrupt: print('Manual break by user')
import os import time import numpy as np url = 'https://api.kraken.com/0/public/Ticker' pair = 'XXBTZUSD' finename = '../../data/{}.csv'.format(pair) if __name__ == '__main__': #Create dump file if not created (not tracked by git) if not os.path.exists('../../data/'): os.makedirs('../../data/') page, now = utils.get_api_result(url, pair) header, data = utils.get_currency(page, now, pair) with open(finename, 'wb') as f: np.savetxt(f, data, header=header) try: while True: page, now = utils.get_api_result(url, pair) header, data = utils.get_currency(page, now, pair) utils.dump_data(f, data) print('{0} data loaded at '.format(pair), now.hour, ':', now.minute, ':', now.second) print('-> Market price: 1{0}={1}{2}'.format(pair[1:4],data[0,6], pair[-3:])) time.sleep(30) except KeyboardInterrupt: print('Manual break by user')
def allocate(self): output.section_start( "Mortgage payoff calculation and projection at retirement") equity = 0.0 debt = 0.0 for n, v in self.d.items(): (val, rate, years) = v home_equity, home_debt = utils.mortgage_payment( val, int(self.t * 12), rate, years) equity += home_equity debt += home_debt output.action( "Keep paying your mortgage as regular to build home equity") output.section_end() assets = self.a.total allocation = dict() equity_percent = self.p.data['risk aversion'] bond_percent = 100 - equity_percent output.section_start( "Investing your assets with chosen asset allocation %d:%d (stocks:bonds)" % (equity_percent, bond_percent)) allocation['equity'] = (assets * equity_percent / 100, STOCK_GROWTH_RATE) allocation['bond'] = (assets * bond_percent / 100, BOND_GROWTH_RATE) output.action( "Re-balance your assets of %s%.2f as %d_%d (stocks_bonds)" % (utils.get_currency(), assets, equity_percent, bond_percent)) utils.piechart("Asset_allocated_now", "Asset allocation now", [n for n, v in allocation.items()], [v[0] for n, v in allocation.items()]) invest = dict() invest['equity'] = self.s * equity_percent / 100 invest['bond'] = self.s * bond_percent / 100 total = utils.fv_allocation(allocation, invest, self.t) allocation['real estate'] = (equity) total += equity output.action("Invest %s%.2f per month for %.2f years" % (utils.get_currency(), self.s, self.t)) output.info("Total assets with proper allocation: %s%.2f" % (utils.get_currency(), total)) output.info("Total debt at retirement: %s%.2f" % (utils.get_currency(), debt)) output.info("Net worth: %s%.2f" % (utils.get_currency(), (total - debt))) utils.piechart("Assets_in_%d_years" % (self.t), "Assets in %d years" % (self.t), [n for n, v in allocation.items()], [v for n, v in allocation.items()]) net_worth = total - debt output.action( "Preserve your net worth %s%.2f by moving to safer assets" % (utils.get_currency(), net_worth)) expense = self.e.get_monthly() years = net_worth / (expense * 12) output.info( "Your net worth will last %d years if you spend %s%.2f monthly as of today." % (years, utils.get_currency(), expense)) if ((years + self.p.getRetireAge()) > LIFE_EXPECTANCY): output.info( "You have a secure retirement considering life expectancy of %d years" % (LIFE_EXPECTANCY)) output.action( "Enjoy your retirement with %s%.2f, withdraw %s%.2f per month." % (utils.get_currency(), net_worth, utils.get_currency(), expense)) else: output.warn( "You will not have enough corpus to last a retired life expectancy of %d years" % (LIFE_EXPECTANCY)) output.action("You need to save more or reduce your expenses") output.section_end()
import numpy as np import pandas as pd from utils import get_currency from nltk import word_tokenize, pos_tag, ne_chunk from nltk.corpus import stopwords # libraries and lists debit_interest = [ 'debit', 'debited', 'paid', 'payment', 'spend', 'spent', 'expense', 'purchase', 'payment' ] credit_interest = [ 'credited', 'credit', 'reversed', 'reverse', 'credited/reversed', 'recieved', 'recieve', 'sent', 'send' ] currency = get_currency() stop_words = set(stopwords.words('english')) acList = ["ac", "account", "account/no", "a/c", "acct"] genericList = [ "hdfc", "icici", "sbi", "kotak", "credit", "debit", "mahindra", "bank", "card", "axis", "citi", "hsbc", "vijaya", "obc", "oriental", "curr", "ac", "account", "account/no", "a/c", "o/s", "acct", "credit", "card", "jun", "jul", "jan", "feb", "mar", "apr", "may", "aug", "sept", "oct", "nov", "dec", "today", "tomorrow", "dear", "customer", "balance", "bal", "info", "bil", "your", "vps", "imps", "ips", "cash", "cashback", "cashbck" ] # utility function def getCurrency(sentences, currency): for s in sentences:
def grow_assets(self): print("\n") output.section_start("Building wealth steadily is not difficult...") output.info("ANALYSIS - Projecting growth of assets") p = self._p b = self._b a = self._a x = list() y = list() y_ = list() start = p.getCurrentAge() + (self.m_for_ef_debt / 12) monthly_surplus = b.get_monthly() if (start > p.getCurrentAge()): output.info( "You can start investing only at the age of %d years after emergency fund and/or debt payoff." % (start)) monthly_surplus = self.surplus if (start > p.getRetireAge()): output.warn( "Unfortunately time to pay off debt or building emergency fund exceeds your retirement age %d." % (p.getRetireAge())) output.warn("You need to delay your retirement by few more years.") quit() time_to_grow = p.getRetireAge() - p.getCurrentAge() - ( self.m_for_ef_debt / 12) risk = p.getRiskNumber() # Take 401k etc. into account monthly_surplus += (self._i.deductions) / 12 output.info( "Your assets will grow in next %.2f years if you regularly invest %s%.2f every month" % (time_to_grow, utils.get_currency(), monthly_surplus)) output.info("Invest %.2f per month for next %.2f years" % (monthly_surplus, time_to_grow)) d = dict() d = a.data.copy() t = utils.fv(d, monthly_surplus / len(d), time_to_grow) if (t > 100000): output.info("You will be a MILLIONAIRE") else: if (t > 900000): output.info("You will be very close to a millionaire") utils.report( "If you invest %s%.2f regularly, your assets will be" % (utils.get_currency(), monthly_surplus), d, t) utils.piechart("FV_regular", "Future Value of Assets if you invest regularly", [n for n, v in d.items()], [v for n, v in d.items()]) e = dict() e = a.data.copy() t = utils.fv(e, 0.0, time_to_grow) utils.report( "If you do not invest the surplus, your assets will remain", e, t) utils.piechart("FV_static", "Future Value of Assets if you do not invest anymore", [n for n, v in e.items()], [v for n, v in e.items()]) output.info("ANALYSIS - Asset projection done....") x = [i for i in range(1, int(time_to_grow))] for j in x: f = a.data.copy() y.append(utils.fv(f, monthly_surplus / len(f), j)) f = a.data.copy() y_.append(utils.fv(f, 0.0, j)) #print(x, y, y_) output.section_end() # update self.surplus for asset allocation self.surplus = monthly_surplus return x, y, y_
def check_pay_debt(self): print("\n") output.section_start("Debt free life means Freedom...") output.info("ANALYSIS - Checking your debt and a payoff plan....") # check for consumer debt d = self._d.unknown b = self._b a = self._a total = 0.0 self.allocation['Debt Payoff'] = 0.0 debt_payment = 0.0 for n, v in d.items(): (val, rate, y) = v if (rate > HIGH_INTEREST_RATE): output.warn("High interest rate for %s: $%.2f @ %.2f" % (n, val, rate)) total += val debt_payment += self._d.payment[n] if (total == 0.0): output.info("Congratulations - You are debt free.") output.info("You can invest %.2f per month and grow your assets." % (b.get_monthly())) output.info("Your current assets") a.report("Assets_after_debt_free") else: #print("\n") output.action("Pay the debt $%.2f in order - " % (total)) for n, v in sorted(d.items(), key=lambda x: x[1][0]): print(" n:%s rate:%.2f value:$%.2f" % (n, v[1], v[0])) # check assets for paying off debt for n, v in sorted(a.data.items(), key=lambda x: x[1][1]): if (total <= 0.0): break (val, rate) = v if (val <= 0.0): continue take = min(val, total) output.action("Use the %s to pay off debt with value $%.2f" % (n, take)) total -= val a.reduce(n, take, rate) self.allocation['Debt Payoff'] += take #print("\n") output.info("Assets after paying off debt.") a.report("Assets_after_paying_off_debt") if (total > 0.0): if (b.get_monthly() <= 0.0): if (self.surplus > 0.0): output.warn( "You can pay off debt only after the emergency fund is built." ) output.action( "Need monthly budget $%.2f to pay off remaining debt $%.2f" % (self.surplus, total)) months = int((total + self.surplus) / self.surplus) self.m_for_ef_debt += months output.info("You will be debt free in %d months." % (self.m_for_ef_debt)) output.info( "You will save %s%.2f of debt payments every month." % (utils.get_currency(), debt_payment)) self.surplus += debt_payment else: output.warn( "You do not have surplus left in your budget to pay off debt. Reduce your expenses." ) else: output.action( "Need monthly budget $%.2f to pay off remaining debt $%.2f" % (b.get_monthly(), total)) months = int((total + b.get_monthly()) / b.get_monthly()) print(" No. of months - %d" % (months)) output.info("You will be debt free in %d months." % (months)) output.info( "You will save %s%.2f of debt payments every month." % (utils.get_currency(), debt_payment)) self.m_for_ef_debt = months self._b.add_expense("Debt Payoff", b.get_monthly()) self.surplus += debt_payment else: output.info("You can be debt-free now.") output.info("ANALYSIS - Done debt payoff plan....") output.section_end()