def get_user_monthly_contrib(self, user_id, yr):
     st_date = datetime.date(year=yr, day=1, month=1)
     end_date = datetime.date(year=yr, day=31, month=12)
     today = datetime.date.today()
     if end_date > today:
         end_date = today
     contrib = [0] * 12
     deduct = [0] * 12
     valid_acc_types = ['Savings', 'Checking', 'Current', 'Other']
     for acc in BankAccount.objects.filter(user=user_id,
                                           acc_type__in=valid_acc_types):
         c = [0] * 12
         d = [0] * 12
         for trans in Transaction.objects.filter(account=acc,
                                                 trans_date__lte=end_date,
                                                 trans_date__gte=st_date):
             if trans.trans_type == 'Credit':
                 c[trans.trans_date.month - 1] += float(trans.amount)
             else:
                 d[trans.trans_date.month - 1] += float(trans.amount)
         for i in range(0, 12):
             contrib[i] += get_in_preferred_currency(
                 c[i], acc.currency, end_date)
             deduct[i] += -1 * get_in_preferred_currency(
                 d[i], acc.currency, end_date)
     return contrib, deduct
 def get_goal_yearly_contrib(self, goal_id, yr):
     st_date = datetime.date(year=yr, day=1, month=1)
     end_date = datetime.date(year=yr, day=31, month=12)
     if end_date > datetime.date.today():
         end_date = datetime.date.today()
     contrib = 0
     deduct = 0
     total = 0
     cash_flows = list()
     valid_acc_types = ['Savings', 'Checking', 'Current', 'Other']
     for obj in BankAccount.objects.filter(goal=goal_id,
                                           acc_type__in=valid_acc_types):
         c = 0
         d = 0
         tot = 0
         for t in Transaction.objects.filter(account=obj,
                                             trans_date__lte=end_date):
             if t.trans_type == 'Credit':
                 if t.trans_date >= st_date:
                     c += float(t.amount)
                     #cash_flows.append((t.trans_date, -1*float(t.amount)))
                 tot += float(t.amount)
             else:
                 if t.trans_date >= st_date:
                     d += -1 * float(t.amount)
                     #cash_flows.append((t.trans_date, float(t.amount)))
                 tot -= float(t.amount)
         contrib += get_in_preferred_currency(c, obj.currency, end_date)
         deduct += get_in_preferred_currency(d, obj.currency, end_date)
         total += get_in_preferred_currency(tot, obj.currency, end_date)
         cash_flows.append(
             (end_date,
              -1 * get_in_preferred_currency(tot, obj.currency, end_date)))
     return cash_flows, contrib, deduct, total
def get_accounts(request):
    template = 'bankaccounts/account_list.html'
    context = dict()
    context['users'] = get_all_users()
    user = None
    context['object_list'] = list()
    context['goal_name_mapping'] = get_all_goals_id_to_name_mapping()
    context['user_name_mapping'] = get_all_users()
    balance = 0
    loan_balance = 0
    accounts = BankAccount.objects.all()
    as_on = None
    for acc in accounts:
        last_trans = Transaction.objects.filter(
            account=acc).order_by('trans_date').last()
        last_trans_dt = None
        if last_trans:
            last_trans_dt = last_trans.trans_date
        acc.last_trans_dt = last_trans_dt

        first_trans = Transaction.objects.filter(
            account=acc).order_by('trans_date').first()
        first_trans_dt = None
        if first_trans:
            first_trans_dt = first_trans.trans_date
        acc.first_trans_dt = first_trans_dt
        acc.preferred_currency_bal = get_in_preferred_currency(
            float(acc.balance), acc.currency, datetime.date.today())
        context['object_list'].append(acc)
        if is_a_loan_account(acc.acc_type):
            loan_balance += get_in_preferred_currency(float(acc.balance),
                                                      acc.currency,
                                                      datetime.date.today())
        else:
            balance += get_in_preferred_currency(float(acc.balance),
                                                 acc.currency,
                                                 datetime.date.today())
        if not as_on:
            as_on = acc.as_on_date
        elif acc.as_on_date:
            as_on = acc.as_on_date if as_on > acc.as_on_date else as_on

    if as_on:
        #context['as_on_date'] = get_preferred_tz(as_on)
        context['as_on_date'] = as_on
    else:
        context['as_on_date'] = 'None'
    context['curr_module_id'] = 'id_bank_acc_module'
    context['preferred_currency_bal'] = round(balance, 2)
    context['preferred_currency_loan_bal'] = round(loan_balance, 2)
    context['goal_name_mapping'] = get_all_goals_id_to_name_mapping()
    context['user_name_mapping'] = get_all_users()
    context['preferred_currency'] = get_preferred_currency_symbol()
    return render(request, template, context)
 def get_value_as_on(self, end_date):
     from .crypto_helper import reconcile_event_based
     from common.models import Coin, HistoricalCoinPrice
     from tasks.tasks import pull_and_store_coin_historical_vals
     today = datetime.date.today()
     if end_date > today:
         end_date = today
     amt = 0
     for crypto in Crypto.objects.filter():
         transactions = Transaction.objects.filter(crypto=crypto,
                                                   trans_date__lte=end_date)
         qty, buy_value, buy_price, realised_gain, unrealised_gain = reconcile_event_based(
             transactions)
         if qty > 0:
             try:
                 coin = Coin.objects.get(symbol=crypto.symbol)
                 try:
                     price = HistoricalCoinPrice.objects.get(coin=coin,
                                                             date=end_date)
                     amt += get_in_preferred_currency(
                         float(price * qty), 'USD', end_date)
                 except HistoricalCoinPrice.DoesNotExist:
                     pull_and_store_coin_historical_vals(
                         crypto.symbol, end_date)
             except Coin.DoesNotExist:
                 pull_and_store_coin_historical_vals(
                     crypto.symbol, end_date)
     return round(amt, 2)
 def get_loan_amount_for_user(self, user_id):
     amt = 0
     valid_acc_types = ['HomeLoan', 'CarLoan', 'PersonalLoan', 'OtherLoan']
     objs = BankAccount.objects.filter(user=user_id,
                                       acc_type__in=valid_acc_types)
     for obj in objs:
         amt += 0 if not obj.balance else get_in_preferred_currency(
             float(obj.balance), obj.currency, datetime.date.today())
     return round(amt, 2)
 def get_amount_for_user(self, user_id):
     amt = 0
     valid_acc_types = ['Savings', 'Checking', 'Current', 'Other']
     objs = BankAccount.objects.filter(user=user_id,
                                       acc_type__in=valid_acc_types)
     for obj in objs:
         amt += 0 if not obj.balance else get_in_preferred_currency(
             float(obj.balance), obj.currency, datetime.date.today())
     return round(amt, 2)
def account_detail(request, id):
    template = 'bankaccounts/account_detail.html'
    context = dict()
    try:
        acc = BankAccount.objects.get(id=id)
        context['curr_module_id'] = 'id_bank_acc_module'
        context['balance_preferred_currency'] = round(
            get_in_preferred_currency(float(acc.balance), acc.currency,
                                      datetime.date.today()), 2)
        goal_name_mapping = get_all_goals_id_to_name_mapping()
        if acc.goal:
            context['goal'] = goal_name_mapping[acc.goal]
        else:
            context['goal'] = None
        user_name_mapping = get_all_users()
        context['user'] = user_name_mapping[acc.user]
        context['preferred_currency'] = get_preferred_currency_symbol()
        context['number'] = acc.number
        context['bank_name'] = acc.bank_name
        context['acc_type'] = acc.acc_type
        context['currency'] = acc.currency
        context['as_on_date'] = acc.as_on_date
        context['start_date'] = acc.start_date
        context['balance'] = acc.balance
        bal_vals = list()
        chart_labels = list()
        balance = 0

        prev_trans = None
        for trans in Transaction.objects.filter(
                account=acc).order_by('trans_date'):
            if trans.trans_type == 'Credit':
                balance += float(trans.amount)
            else:
                balance -= float(trans.amount)
            balance = round(balance, 2)
            if len(bal_vals) == 0:
                bal_vals.append(balance)
                chart_labels.append(trans.trans_date.strftime('%Y-%m-%d'))
            else:
                if float(
                        trans.amount
                ) > balance / 10 or prev_trans.month != trans.trans_date.month or prev_trans.year != trans.trans_date.year:
                    bal_vals.append(balance)
                    chart_labels.append(trans.trans_date.strftime('%Y-%m-%d'))
            prev_trans = trans.trans_date
        if len(bal_vals) > 0:
            bal_vals.append(balance)
            chart_labels.append(datetime.date.today().strftime('%Y-%m-%d'))
        context['bal_vals'] = bal_vals
        context['chart_labels'] = chart_labels
        return render(request, template, context)
    except BankAccount.DoesNotExist:
        return HttpResponseRedirect(reverse('bankaccounts:account-list'))
 def get_no_goal_amount(self, user_id=None):
     amt = 0
     valid_acc_types = ['Savings', 'Checking', 'Current', 'Other']
     if user_id:
         objs = BankAccount.objects.filter(user=user_id,
                                           acc_type__in=valid_acc_types)
     else:
         objs = BankAccount.objects.filter(acc_type__in=valid_acc_types)
     for obj in objs:
         if not obj.goal:
             amt += 0 if not obj.balance else get_in_preferred_currency(
                 float(obj.balance), obj.currency, datetime.date.today())
     return Decimal(amt)
 def get_user_yearly_contrib(self, user_id, yr):
     st_date = datetime.date(year=yr, day=1, month=1)
     end_date = datetime.date(year=yr, day=31, month=12)
     today = datetime.date.today()
     if end_date > today:
         end_date = today
     contrib = 0
     deduct = 0
     valid_acc_types = ['Savings', 'Checking', 'Current', 'Other']
     for acc in BankAccount.objects.filter(user=user_id,
                                           acc_type__in=valid_acc_types):
         c = 0
         d = 0
         for trans in Transaction.objects.filter(account=acc,
                                                 trans_date__lte=end_date,
                                                 trans_date__gte=st_date):
             if trans.trans_type == 'Credit':
                 c += float(trans.amount)
             else:
                 d += float(trans.amount)
         contrib += get_in_preferred_currency(c, acc.currency, end_date)
         deduct += get_in_preferred_currency(d, acc.currency, end_date)
     return contrib, -1 * deduct
    def get_goal_yearly_contrib(self, goal_id, yr):
        st_date = datetime.date(year=yr, day=1, month=1)
        end_date = datetime.date(year=yr, day=31, month=12)
        if end_date > datetime.date.today():
            end_date = datetime.date.today()
        contrib = 0
        deduct = 0
        total = 0
        cash_flows = list()

        for cobj in Crypto.objects.filter(goal=goal_id):
            tu = 0
            for t in Transaction.objects.filter(
                    crypto=cobj,
                    trans_date__lte=end_date).order_by('trans_date'):
                if t.trans_date >= st_date:
                    if t.trans_type == 'Buy' or t.trans_type == 'Receive':
                        contrib += float(t.trans_price)
                        cash_flows.append(
                            (t.trans_date, -1 * float(t.trans_price)))
                        tu += t.units
                    else:
                        cash_flows.append((t.trans_date, float(t.trans_price)))
                        deduct += -1 * float(t.trans_price)
                        tu -= t.units
                else:
                    if t.trans_type == 'Buy' or t.trans_type == 'Receive':
                        tu += t.units
                    else:
                        tu -= t.units
            if tu > 0:
                from common.models import Coin, HistoricalCoinPrice
                try:
                    coin = Coin.objects.get(symbol=cobj.symbol)
                    try:
                        hcp = HistoricalCoinPrice.objects.get(coin=coin,
                                                              date=end_date)
                        total += float(hcp.price) * float(tu) * float(
                            get_in_preferred_currency(1, 'USD'))
                    except HistoricalCoinPrice.DoesNotExist:
                        from tasks.tasks import pull_and_store_coin_historical_vals
                        pull_and_store_coin_historical_vals(
                            cobj.symbol, end_date)
                except Coin.DoesNotExist:
                    print(
                        f'coin not tracked for historical prices {cobj.symbol}'
                    )
        return cash_flows, contrib, deduct, total
 def get_loan_value_as_on(self, end_date):
     today = datetime.date.today()
     if end_date > today:
         end_date = today
     amt = 0
     valid_acc_types = ['HomeLoan', 'CarLoan', 'PersonalLoan', 'OtherLoan']
     for acc in BankAccount.objects.filter(acc_type__in=valid_acc_types):
         b_amt = 0
         for trans in Transaction.objects.filter(account=acc,
                                                 trans_date__lte=end_date):
             if trans.trans_type == 'Credit':
                 b_amt += float(trans.amount)
             else:
                 b_amt -= float(trans.amount)
         amt += get_in_preferred_currency(b_amt, acc.currency, end_date)
     return round(amt, 2)
Example #12
0
def update_crypto(co, latest_prices=None):
    latest_price = None
    latest_time = None
    if latest_prices:
        if co.symbol in latest_prices:
            latest_price = latest_prices.get(co.symbol)['price']
            latest_time = latest_prices.get(co.symbol)['time']
    if not latest_price:
        latest_price, latest_time = get_price(co.symbol)

    if latest_price:
        latest_prices[co.symbol] = {'price': latest_price, 'time': latest_time}
        conv_rate = get_in_preferred_currency(1.0, 'USD',
                                              datetime.date.today())
        transactions = Transaction.objects.filter(
            crypto=co).order_by('trans_date')
        qty, buy_value, buy_price, realised_gain, unrealised_gain = reconcile_event_based(
            transactions, False, latest_price, conv_rate)
        print(
            f'qty {qty}, buy_value {buy_value}, buy_price {buy_price}, realised_gain {realised_gain}, unrealised_gain {unrealised_gain} in update_crypto'
        )
        co.latest_value = float(latest_price) * float(qty) * float(conv_rate)
        co.buy_price = buy_price
        co.buy_value = buy_value
        co.realised_gain = realised_gain
        co.unrealised_gain = unrealised_gain
        co.units = qty
        co.latest_price = latest_price
        co.as_on_date = latest_time
        cash_flows = list()
        for t in transactions:
            if t.trans_type == 'Buy':
                cash_flows.append((t.trans_date, -1 * float(t.trans_price)))
            else:
                cash_flows.append((t.trans_date, float(t.trans_price)))
        co.save()
        if qty > 0:
            cash_flows.append((datetime.date.today(), float(co.latest_value)))
        try:
            roi = xirr(cash_flows, 0.1) * 100
            roi = round(roi, 2)
            co.xirr = roi
        except Exception as ex:
            print(f'exception finding xirr {ex}')
            co.xirr = 0
    co.save()
Example #13
0
def crypto_detail(request, id):
    template = 'crypto/crypto_detail.html'
    context = dict()
    try:
        crypto = Crypto.objects.get(id=id)
        context['curr_module_id'] = CryptoInterface.get_module_id()
        context['latest_value_preferred_currency'] = round(
            crypto.latest_value, 2)
        goal_name_mapping = get_all_goals_id_to_name_mapping()
        if crypto.goal:
            context['goal'] = goal_name_mapping[crypto.goal]
        else:
            context['goal'] = None
        user_name_mapping = get_all_users()
        context['user'] = user_name_mapping[crypto.user]
        context['preferred_currency'] = get_preferred_currency_symbol()
        context['symbol'] = crypto.symbol
        context['as_on_date'] = crypto.as_on_date
        context['latest_value'] = crypto.latest_value
        bal_vals = list()
        price_vals = list()
        chart_labels = list()
        balance = 0

        prev_trans = None

        today = datetime.date.today()
        end_date = today
        transactions = Transaction.objects.filter(
            crypto=crypto).order_by('trans_date')
        if len(transactions) > 0:
            #bal_vals.append(transactions[0].trans_price)
            #chart_labels.append(transactions[0].trans_date.strftime('%Y-%m-%d'))
            new_trans = list()
            start_day = transactions[0].trans_date
            start_day = start_day.replace(day=1)
            start_day = start_day + relativedelta(months=1)
            i = 0
            try:
                coin = Coin.objects.get(symbol=crypto.symbol)
                while start_day < end_date:
                    print(f'start_day{start_day}')
                    while i < len(transactions):
                        if transactions[i].trans_date <= start_day:
                            new_trans.append(transactions[i])
                            i += 1
                        else:
                            break
                    qty, buy_value, buy_price, realised_gain, unrealised_gain = reconcile_event_based(
                        transactions)
                    print(f'quantity is {qty} as of {start_day}')
                    if qty > 0:
                        try:
                            hcp = HistoricalCoinPrice.objects.get(
                                coin=coin, date=start_day)
                            amt = get_in_preferred_currency(
                                float(hcp.price * qty), 'USD', start_day)
                            bal_vals.append(amt)
                            price_vals.append(float(hcp.price))
                            chart_labels.append(start_day.strftime('%Y-%m-%d'))
                        except HistoricalCoinPrice.DoesNotExist:
                            pull_and_store_coin_historical_vals(
                                crypto.symbol, start_day)

                    start_day = start_day + relativedelta(months=1)
                if today.day != 1 and len(bal_vals) > 0:
                    bal_vals.append(float(crypto.latest_value))
                    chart_labels.append(crypto.as_on_date.strftime('%Y-%m-%d'))
                    price_vals.append(float(crypto.latest_price))

            except Coin.DoesNotExist:
                pull_and_store_coin_historical_vals(crypto.symbol, start_day)

        context['bal_vals'] = bal_vals
        context['chart_labels'] = chart_labels
        context['price_vals'] = price_vals
        print(context)
        return render(request, template, context)
    except Crypto.DoesNotExist:
        return HttpResponseRedirect(reverse('crypto:crypto-list'))