Example #1
0
 def get_orders(self):
     if self.logged_in:
         ret = dict()
         order_list = get_all_stock_orders()
         for order in order_list:
             ot = get_symbol_by_url(order['instrument'])
             if order['state'] == 'filled':
                 try:
                     if ot not in ret:
                         ret[ot] = list()
                     o = dict()
                     o['type'] = order['side']
                     o['date'] = self.get_date_from_string(
                         order['last_transaction_at'])
                     o['quantity'] = get_float_or_none_from_string(
                         order['cumulative_quantity'])
                     o['div_reinv'] = False
                     if 'drip_dividend_id' in order:
                         o['div_reinv'] = True if order[
                             'drip_dividend_id'] else False
                     o['price'] = get_float_or_none_from_string(
                         order['average_price'])
                     o['conv_price'] = get_conversion_rate(
                         'USD', 'INR', o['date'])
                     o['trans_price'] = o['quantity'] * o['price'] * o[
                         'conv_price']
                     ret[ot].append(o)
                 except Exception as ex:
                     print(f'Exception parsing order {order}: {ex}')
         return ret
     else:
         raise Exception('not logged in')
def reconcile_401k():
    accounts = Account401K.objects.all()
    cash_flows = list()
    for account in accounts:
        total_units = 0
        employee_contrib = 0
        employer_contrib = 0
        latest_date = None
        latest_nav = 0
        for transaction in Transaction401K.objects.filter(
                account=account).order_by('trans_date'):
            total_units += transaction.units
            employee_contrib += transaction.employee_contribution
            employer_contrib += transaction.employer_contribution
            if not latest_date:
                latest_date = transaction.trans_date
                latest_nav = (
                    transaction.employee_contribution +
                    transaction.employer_contribution) / transaction.units
            else:
                if latest_date < transaction.trans_date:
                    latest_date = transaction.trans_date
                    latest_nav = (
                        transaction.employee_contribution +
                        transaction.employer_contribution) / transaction.units
            cash_flows.append((transaction.trans_date,
                               -1 * float(transaction.employee_contribution +
                                          transaction.employer_contribution)))

        account.units = total_units
        account.employee_contribution = employee_contrib
        account.employer_contribution = employer_contrib
        account.total = employee_contrib + employer_contrib

        if latest_date:
            nav_date, nav_value = get_latest_month_end_nav(account.id)
            if nav_date and nav_date > latest_date:
                latest_date = nav_date
                latest_nav = nav_value
            fx = get_conversion_rate('USD', 'INR', latest_date)
            account.latest_value = float(latest_nav) * float(
                account.units) * fx
            account.gain = float(
                account.latest_value) - float(account.total) * fx
            if len(cash_flows) > 1:
                cash_flows.append(
                    (latest_date, float(latest_nav) * float(account.units)))
                roi = xirr(cash_flows, 0.1) * 100
                roi = round(roi, 2)
                account.roi = roi
            else:
                account.roi = 0
            account.nav = latest_nav
            account.nav_date = latest_date
        else:
            account.latest_value = 0
            account.roi = 0
            account.nav = 0
            account.nav_date = None
        account.save()
Example #3
0
 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
     for obj in Account401K.objects.filter(user=user_id):
         for trans in Transaction401K.objects.filter(
                 account=obj, trans_date__gte=st_date,
                 trans_date__lte=end_date):
             conv_rate = 1
             conv_val = get_conversion_rate('USD', 'INR', trans.trans_date)
             if conv_val:
                 conv_rate = conv_val
             else:
                 print(
                     f'failed to get conversion rate from USD to INR for date {trans.trans_date}'
                 )
             contrib[
                 trans.trans_date.month -
                 1] += float(trans.employee_contribution +
                             trans.employer_contribution) * float(conv_rate)
     return contrib, deduct
Example #4
0
    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 obj in Account401K.objects.filter(goal=goal_id):
            qty = 0
            for trans in Transaction401K.objects.filter(
                    account=obj, trans_date__lte=end_date):
                if trans.trans_date >= st_date:
                    conv_rate = 1
                    conv_val = get_conversion_rate('USD', 'INR',
                                                   trans.trans_date)
                    if conv_val:
                        conv_rate = conv_val
                    else:
                        print(
                            f'failed to get conversion rate from USD to INR for date {trans.trans_date}'
                        )
                    v = float(trans.employee_contribution +
                              trans.employer_contribution) * float(conv_rate)
                    contrib += v
                    cash_flows.append((trans.trans_date, -1 * v))
                qty += float(trans.units)
            if qty > 0:
                nav_objs = NAVHistory.objects.filter(
                    account=obj,
                    nav_date__lte=end_date).order_by('-nav_date')  #descending
                conv_rate = 1
                conv_val = get_conversion_rate('USD', 'INR',
                                               nav_objs[0].nav_date)
                if conv_val:
                    conv_rate = conv_val
                else:
                    print(
                        f'failed to get conversion rate from USD to INR for date {nav_objs[0].nav_date}'
                    )

                total += float(nav_objs[0].nav_value) * qty * float(conv_rate)
        return cash_flows, contrib, deduct, total
Example #5
0
def add_untracked_transactions():
    trans_path = os.path.join(settings.MEDIA_ROOT,
                              'untracked_shares_transactions')
    if os.path.exists(trans_path):
        trans_file = os.path.join(trans_path, 'transactions.csv')
        if os.path.exists(trans_file):
            with open(trans_file, 'r') as csv_file:
                csv_reader = csv.DictReader(csv_file)
                for row in csv_reader:
                    if row['trading_symbol'] != 'IGNORETRANS':
                        print(row)
                        #user,exchange,trade_date,trading_symbol,segment,trade_type,quantity,price,order_id,notes,broker
                        try:
                            exchange = row['exchange']
                            symbol = row['trading_symbol']
                            trans_type = row['trade_type']
                            trans_type = 'Buy' if trans_type.lower(
                            ) == 'buy' else 'Sell'
                            user = int(row['user'])
                            user_name = get_user_name_from_id(user)
                            if not user_name:
                                raise Exception('User %s doesnt exist' %
                                                str(user))
                            broker = row['broker']
                            notes = row['notes']
                            date = get_date_or_none_from_string(
                                row['trade_date'], format='%d/%m/%Y')
                            quantity = get_float_or_zero_from_string(
                                row['quantity'])
                            price = get_float_or_zero_from_string(row['price'])
                            if row['order_id'] and row['order_id'] != '':
                                if not notes or notes == '':
                                    notes = 'order id:' + row['order_id']
                                else:
                                    notes = notes + '. order id:' + row[
                                        'order_id']

                            if exchange == 'NSE' or exchange == 'BSE':
                                conversion_rate = 1
                            elif exchange == 'NASDAQ' or exchange == 'NYSE':
                                conversion_rate = get_conversion_rate(
                                    'USD', 'INR', date)
                            else:
                                raise Exception('unsupported exchange %s' %
                                                exchange)
                            insert_trans_entry(exchange, symbol, user,
                                               trans_type, quantity, price,
                                               date, notes, broker,
                                               conversion_rate)
                        except Exception as ex:
                            print(f'Exception adding transaction {ex}')
        else:
            print(f'untracked shares transactions file not present')
    else:
        print(f'untracked shares transactions folder not present')
 def get(self,
         request,
         year,
         month,
         day,
         from_currency,
         to_currency,
         format=None):
     data = dict()
     date = datetime.date(year=year, month=month, day=day)
     ret = get_conversion_rate(from_currency, to_currency, date)
     print(ret)
     data[convert_date_to_string(date)] = ret
     return Response(data)
Example #7
0
def update_latest_vals(espp_obj):
    start = datetime.date.today()+relativedelta(days=-5)
    end = datetime.date.today()
    sold_units = 0
    realised_gain = 0
    cash_flows = list()
    cash_flows.append((espp_obj.purchase_date, -1*float(espp_obj.total_purchase_price)))
    for sell_trans in EsppSellTransactions.objects.filter(espp=espp_obj):
        sold_units += sell_trans.units
        realised_gain += sell_trans.realised_gain
        cash_flows.append((sell_trans.trans_date, float(sell_trans.trans_price)))
    try:
        _ = Stock.objects.get(exchange=espp_obj.exchange, symbol=espp_obj.symbol)
    except Stock.DoesNotExist:
        _ = Stock.objects.create(
                exchange = espp_obj.exchange,
                symbol=espp_obj.symbol,
                etf=False,
                collection_start_date=datetime.date.today()
            )
    remaining_units = espp_obj.shares_purchased - sold_units
    espp_obj.shares_avail_for_sale = remaining_units
    espp_obj.realised_gain = realised_gain
    if remaining_units > 0:
        vals = get_latest_vals(espp_obj.symbol, espp_obj.exchange, start, end)
        print('vals', vals)
        if vals:
            for k, v in vals.items():
                if k and v:
                    if not espp_obj.as_on_date or k > espp_obj.as_on_date:
                        espp_obj.as_on_date = k
                        espp_obj.latest_price = v
                        if espp_obj.exchange == 'NASDAQ':
                            espp_obj.latest_conversion_rate = get_conversion_rate('USD', 'INR', k)
                        else:
                            espp_obj.latest_conversion_rate = 1
                        espp_obj.latest_value = float(espp_obj.latest_price) * float(espp_obj.latest_conversion_rate) * float(espp_obj.shares_avail_for_sale)
                        espp_obj.unrealised_gain = float(espp_obj.latest_value) - (float(espp_obj.purchase_price) * float(espp_obj.latest_conversion_rate) * float(espp_obj.shares_avail_for_sale))
        if espp_obj.latest_value and espp_obj.latest_value > 0:
            cash_flows.append((datetime.date.today(), float(espp_obj.latest_value)))
            x = xirr(cash_flows, 0.1)*100
            espp_obj.xirr = x
    else:
        espp_obj.latest_value = 0
        espp_obj.xirr = 0
        
    espp_obj.save()
    print('done with update request')
def get_yearly_contribution(id, currency='INR'):
    data = dict()
    years = list()
    er_contrib = list()
    em_contrib = list()
    int_contrib = list()
    total = list()
    try:
        account = Account401K.objects.get(id=id)
        for trans in Transaction401K.objects.filter(
                account=account).order_by('trans_date'):
            yr = trans.trans_date.year
            if yr not in years:
                years.append(yr)
                er_contrib.append(0)
                em_contrib.append(0)
                int_contrib.append(0)
                total.append(0)
            ind = years.index(yr)
            er_contrib[ind] += float(trans.employer_contribution)
            em_contrib[ind] += float(trans.employee_contribution)

        for i, yr in enumerate(years):
            dt = datetime.date(year=yr, month=12, day=31)
            if dt > datetime.date.today():
                dt = datetime.date.today()
            total[i] = int(
                get_r401k_value_as_on_for_account(account, dt, currency))
            fr = get_conversion_rate('USD', currency, dt)
            er_contrib[i] *= fr
            em_contrib[i] *= fr
            er_contrib[i] = int(er_contrib[i])
            em_contrib[i] = int(em_contrib[i])
            if i != 0:
                int_contrib[i] = total[i] - total[
                    i - 1] - em_contrib[i] - er_contrib[i]
            else:
                int_contrib[i] = total[i] - em_contrib[i] - er_contrib[i]
        data['years'] = years
        data['er'] = er_contrib
        data['em'] = em_contrib
        data['int'] = int_contrib
        data['total'] = total

    except Account401K.DoesNotExist:
        print(f'no object with id {str(id)}) found')
    return data
def get_r401k_value_as_on_for_account(account, dt, currency):
    latest_nav = 0
    latest_nav_date = None
    total_units = 0
    for trans in Transaction401K.objects.filter(account=account,
                                                trans_date__lte=dt):
        if latest_nav == 0:
            latest_nav = (trans.employee_contribution +
                          trans.employer_contribution) / trans.units
            latest_nav_date = trans.trans_date
        total_units += trans.units
    if total_units == 0:
        return 0
    #check if nav table has latest value
    checkfrom = datetime.date(day=1, month=dt.month, year=dt.year)
    use_month = dt.month
    use_yr = dt.year
    if dt.month == 12:
        use_month = 1
        use_yr += 1
    else:
        use_month += 1
    checkto = datetime.date(day=1, month=use_month,
                            year=use_yr) + relativedelta(days=-1)
    print(
        f"checking nav history table for data between {checkfrom} and {checkto}"
    )
    for nav_h in NAVHistory.objects.filter(
            account=account, nav_date__lte=checkto,
            nav_date__gte=latest_nav_date).order_by('-nav_date'):
        print(f'found newer date {nav_h.nav_date} nav {str(nav_h.nav_value)}')
        latest_nav = nav_h.nav_value
        latest_nav_date = nav_h.nav_date
        break
    fr = 1
    if currency != 'USD':
        fr = get_conversion_rate('USD', currency, dt)
    print(
        f'using units {str(total_units)}, forex rate {str(fr)}, nav {str(latest_nav)} on {latest_nav_date} for total calculation'
    )
    total_value = float(total_units) * float(latest_nav) * float(fr)

    return round(total_value, 2)
Example #10
0
def update_latest_vals(rsu_obj):
    start = datetime.date.today() + relativedelta(days=-5)
    end = datetime.date.today()
    rsu_award = rsu_obj.award
    rg = 0
    su = 0
    for st in RSUSellTransactions.objects.filter(rsu_vest=rsu_obj):
        su += float(st.units)
        st.trans_price = float(st.price) * float(st.units) * float(
            st.conversion_rate)
        st.realised_gain = float(
            st.trans_price) - float(rsu_obj.aquisition_price) * float(
                st.units) * float(rsu_obj.conversion_rate)
        rg += st.realised_gain
        st.save()
    rsu_obj.realised_gain = rg
    rsu_obj.unsold_shares = float(rsu_obj.shares_for_sale) - su
    rsu_obj.tax_at_vest = float(rsu_obj.shares_vested -
                                rsu_obj.shares_for_sale) * float(
                                    rsu_obj.conversion_rate) * float(
                                        rsu_obj.aquisition_price)
    if rsu_obj.unsold_shares > 0:
        vals = get_latest_vals(rsu_award.symbol, rsu_award.exchange, start,
                               end)
        if vals:
            for k, v in vals.items():
                if k and v:
                    if not rsu_obj.as_on_date or k > rsu_obj.as_on_date:
                        rsu_obj.as_on_date = k
                        rsu_obj.latest_price = v
                        if rsu_award.exchange == 'NASDAQ':
                            rsu_obj.latest_conversion_rate = get_conversion_rate(
                                'USD', 'INR', k)
                        else:
                            rsu_obj.latest_conversion_rate = 1
    rsu_obj.latest_value = float(rsu_obj.latest_price) * float(
        rsu_obj.latest_conversion_rate) * float(rsu_obj.unsold_shares)
    rsu_obj.unrealised_gain = rsu_obj.latest_value - float(
        rsu_obj.unsold_shares) * float(rsu_obj.conversion_rate) * float(
            rsu_obj.aquisition_price)
    rsu_obj.save()
Example #11
0
    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()
        cash_flows = list()
        contrib = 0
        deduct = 0
        total = 0

        for share_obj in Share.objects.filter(goal=goal_id):
            transactions = Transactions.objects.filter(share=share_obj, trans_date__lte=end_date)
            stock = Stock.objects.get(exchange=share_obj.exchange, symbol=share_obj.symbol)
            bonuses = Bonusv2.objects.filter(stock=stock, record_date__lte=end_date)
            splits = Splitv2.objects.filter(stock=stock, ex_date__lte=end_date)
            round_qty_to_int = True if share_obj.exchange in ['NSE', 'BSE', 'NSE/BSE'] else False
            qty, buy_value, buy_price, realised_gain, unrealised_gain = reconcile_event_based(transactions, bonuses, splits, round_qty_to_int=round_qty_to_int, latest_price=share_obj.latest_price, latest_conversion_rate=share_obj.conversion_rate)
            for t in transactions:
                if t.trans_date >= st_date:
                    if t.trans_type == 'Buy':
                        cash_flows.append((t.trans_date, -1*float(t.trans_price)))
                        contrib += float(t.trans_price)
                    else:
                        cash_flows.append((t.trans_date, float(t.trans_price)))
                        deduct += -1*float(t.trans_price)
            if qty > 0:
                year_end_value_vals = get_historical_stock_price_based_on_symbol(share_obj.symbol, share_obj.exchange, end_date+relativedelta(days=-5), end_date)
                if year_end_value_vals:
                    conv_rate = 1
                    if share_obj.exchange == 'NASDAQ' or share_obj.exchange == 'NYSE':
                        conv_val = get_conversion_rate('USD', 'INR', end_date)
                        if conv_val:
                            conv_rate = conv_val
                        for k,v in year_end_value_vals.items():
                            total += float(v)*float(conv_rate)*float(qty)
                            break
                else:
                    print(f'failed to get year end values for {share_obj.exchange} {share_obj.symbol} {end_date}')            
        return cash_flows, contrib, deduct, total
Example #12
0
def add_transaction(request):
    template = 'shares/add_transaction.html'
    if request.method == 'POST':
        if "submit" in request.POST:
            exchange = request.POST['exchange']
            symbol = request.POST['symbol']
            user = request.POST['user']
            print('user is of type:',type(user))
            trans_date = get_datetime_or_none_from_string(request.POST['trans_date'])
            trans_type = request.POST['trans_type']
            price = get_float_or_none_from_string(request.POST['price'])
            quantity = get_float_or_none_from_string(request.POST['quantity'])
            conversion_rate = get_float_or_none_from_string(request.POST['conversion_rate'])
            trans_price = get_float_or_none_from_string(request.POST['trans_price'])
            broker = request.POST['broker']
            notes = request.POST['notes']
            insert_trans_entry(exchange, symbol, user, trans_type, quantity, price, trans_date, notes, broker, conversion_rate, trans_price)
        else:
            print('fetching exchange price')
            exchange = request.POST['exchange']
            symbol = request.POST['symbol']
            user = request.POST['user']
            trans_date = get_datetime_or_none_from_string(request.POST['trans_date'])
            exchange_rate = 1
            if exchange == 'NASDAQ' or exchange == 'NYSE':
                exchange_rate = get_conversion_rate('USD', 'INR', trans_date)
            users = get_all_users()
            trans_type = request.POST['trans_type']
            price = get_float_or_none_from_string(request.POST['price'])
            quantity = get_float_or_none_from_string(request.POST['quantity'])
            context = {'users':users, 'operation': 'Add Transaction', 'conversion_rate':exchange_rate, 'curr_module_id': 'id_shares_module',
                        'trans_date':trans_date.strftime("%Y-%m-%d"), 'user':user, 'exchange':exchange, 'symbol':symbol, 'trans_type':trans_type,
                        'price':price, 'quantity':quantity}
            return render(request, template, context)

    users = get_all_users()
    context = {'users':users, 'operation': 'Add Transaction', 'conversion_rate':1, 'curr_module_id': 'id_shares_module'}
    return render(request, template, context)
 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 aw_obj in RSUAward.objects.filter(goal=goal_id):
         for rsu_obj in RestrictedStockUnits.objects.filter(award=aw_obj, vest_date__lte=end_date):
             units = rsu_obj.shares_for_sale
             if rsu_obj.vest_date >= st_date:
                 current_cost = float(rsu_obj.shares_for_sale*rsu_obj.aquisition_price*rsu_obj.conversion_rate)
                 contrib += current_cost
                 cash_flows.append((rsu_obj.vest_date, -1*current_cost))
             for st in RSUSellTransactions.objects.filter(rsu_vest=rsu_obj, trans_date__lte=end_date):
                 if st.trans_date >= st_date:
                     cash_flows.append((st.trans_date, float(st.trans_price)))
                     deduct += -1*float(st.trans_price)
                 units -= st.units
                     
             if units > 0:
                 year_end_value_vals = get_historical_stock_price_based_on_symbol(aw_obj.symbol, aw_obj.exchange, end_date+relativedelta(days=-5), end_date)
                 if year_end_value_vals:
                     conv_rate = 1
                     if aw_obj.exchange == 'NASDAQ' or aw_obj.exchange == 'NYSE':
                         conv_val = get_conversion_rate('USD', 'INR', end_date)
                         if conv_val:
                             conv_rate = conv_val
                         for k,v in year_end_value_vals.items():
                             total += float(v)*float(conv_rate)*float(units)
                             break
                 else:
                     print(f'failed to get year end values for {aw_obj.exchange} {aw_obj.symbol} {end_date}')
     return cash_flows, contrib, deduct, total
Example #14
0
def update_shares_latest_val():
    start = datetime.date.today() + relativedelta(days=-5)
    end = datetime.date.today()
    share_objs = Share.objects.all()
    for share_obj in share_objs:
        if share_obj.quantity > 0:
            latest_date = None
            latest_val = None
            if (share_obj.as_on_date and share_obj.as_on_date <
                    datetime.date.today()) or not share_obj.as_on_date:
                vals = get_latest_vals(share_obj.symbol, share_obj.exchange,
                                       start, end, share_obj.etf)
                if vals:
                    for k, v in vals.items():
                        if k and v:
                            if not latest_date or k > latest_date:
                                latest_date = k
                                latest_val = v
                else:
                    print(
                        f'Couldnt get latest value for {share_obj.symbol} {share_obj.exchange}'
                    )
                    if share_obj.exchange == 'BSE':
                        isin = None
                        for trans in Transactions.objects.filter(
                                share=share_obj):
                            isin = get_isin_from_bhav_copy(
                                share_obj.symbol, trans.trans_date)
                            if isin:
                                break
                        if isin:
                            nse_bse_data = get_nse_bse(None, None, isin)
                            if nse_bse_data and 'nse' in nse_bse_data:
                                print(
                                    f'checking if share with symbol {nse_bse_data["nse"]} exists'
                                )
                                isin_objs = Share.objects.filter(
                                    exchange='NSE/BSE',
                                    symbol=nse_bse_data['nse'])
                                if len(isin_objs) == 1:
                                    move_trans(share_obj, isin_objs[0], True)
                                    continue

                                else:
                                    nse_objs = Share.objects.filter(
                                        exchange='NSE',
                                        symbol=nse_bse_data['nse'])
                                    if len(nse_objs) == 1:
                                        move_trans(share_obj, nse_objs[0],
                                                   True)
                                        nse_objs[0].exchange = 'NSE/BSE'
                                        nse_objs[0].save()
                                        continue

                            if 'bse' in nse_bse_data:
                                try:
                                    bse_obj = Share.objects.get(
                                        exchange='BSE',
                                        symbol=nse_bse_data['bse'])
                                    move_trans(share_obj, bse_obj, True)
                                except Share.DoesNotExist:
                                    share_obj.symbol = nse_bse_data['bse']
                                    share_obj.save()
                                continue
                        else:
                            print(
                                f'couldnt find isin for {share_obj.symbol} {share_obj.exchange} using transaction date bhav copy'
                            )
                    elif share_obj.exchange == 'NSE':
                        valid, _ = check_nse_valid(share_obj.symbol)
                        if not valid:
                            trans = Transactions.objects.filter(
                                share=share_obj).order_by('-trans_date')
                            if len(trans) > 0:
                                bhavcopy_symbol = share_obj.symbol
                                while True:
                                    nh = NSEHistorical(bhavcopy_symbol,
                                                       trans[0].trans_date,
                                                       True)
                                    isin = nh.get_isin_from_bhav_copy()
                                    if isin:
                                        n = NSE('')
                                        symbol = n.get_symbol(isin)
                                        if symbol:
                                            nse_objs = Share.objects.filter(
                                                exchange='NSE', symbol=symbol)
                                            if len(nse_objs) == 1:
                                                move_trans(
                                                    share_obj, nse_objs[0],
                                                    True)
                                            else:
                                                nse_objs = Share.objects.filter(
                                                    exchange='NSE/BSE',
                                                    symbol=symbol)
                                                if len(nse_objs) == 1:
                                                    move_trans(
                                                        share_obj, nse_objs[0],
                                                        True)
                                                else:
                                                    share_obj.symbol = symbol
                                                    share_obj.save()
                                                    break
                                        else:
                                            print(
                                                f'Failed to get symbol from isin {isin}'
                                            )
                                    else:
                                        print(
                                            f'couldnt find isin for {share_obj.symbol} {share_obj.exchange} using transaction date bhav copy'
                                        )
                                        if '-' in bhavcopy_symbol:
                                            bhavcopy_symbol = bhavcopy_symbol[
                                                0:bhavcopy_symbol.rfind('-')]
                                        else:
                                            break
                if latest_date and latest_val:
                    share_obj.as_on_date = latest_date
                    if share_obj.exchange == 'NASDAQ':
                        share_obj.conversion_rate = get_conversion_rate(
                            'USD', 'INR', k)
                    else:
                        share_obj.conversion_rate = 1
                    share_obj.latest_value = float(latest_val) * float(
                        share_obj.conversion_rate) * float(share_obj.quantity)
                    share_obj.latest_price = float(latest_val)
                    share_obj.save()
                else:
                    create_alert(
                        summary=share_obj.exchange + ':' + share_obj.symbol +
                        ' - Failed to get latest value',
                        content=share_obj.exchange + ':' + share_obj.symbol +
                        ' - Failed to get latest value',
                        severity=Severity.warning,
                        alert_type="Action")
                if share_obj.latest_value:
                    share_obj.gain = float(share_obj.latest_value) - float(
                        share_obj.buy_value)
                    share_obj.save()
        elif share_obj.quantity == 0:
            share_obj.latest_value = 0
            share_obj.latest_price = 0
            share_obj.gain = 0
            share_obj.roi = 0
            share_obj.as_on_date = datetime.date.today()
            share_obj.save()
        else:
            print(f'ignoring {share_obj.symbol} with -ve quantity')
Example #15
0
def update_transaction(request, id, trans_id):
    template = 'crypto/update_transaction.html'
    try:
        cobj = Crypto.objects.get(id=id)
        trans = None
        try:
            trans = Transaction.objects.get(crypto=cobj, id=trans_id)
        except Transaction.DoesNotExist:
            return HttpResponseRedirect(reverse('crypto:crypto-list'))
        symbol = cobj.symbol
        user = cobj.user
        currencies = supported_currencies_as_list()
        users = get_all_users()
        preferred_currency = get_preferred_currency()
        if request.method == 'POST':
            if "submit" in request.POST:
                trans_date = get_datetime_or_none_from_string(
                    request.POST['trans_date'])
                trans_type = request.POST['trans_type']
                price = get_float_or_none_from_string(request.POST['price'])
                quantity = get_float_or_none_from_string(
                    request.POST['quantity'])
                conversion_rate = get_float_or_none_from_string(
                    request.POST['conversion_rate'])
                trans_price = get_float_or_none_from_string(
                    request.POST['trans_price'])
                broker = request.POST['broker']
                notes = request.POST['notes']
                chosen_currency = request.POST['currency']
                fees = request.POST['charges']
                trans.trans_type = trans_type
                trans.price = price
                trans.units = quantity
                trans.conversion_rate = conversion_rate
                trans.trans_price = trans_price
                trans.broker = broker
                trans.notes = notes
                trans.fees = fees
                trans.buy_currency = chosen_currency
                trans.save()
                update_crypto_for_user(trans.crypto.user)
            else:
                print('fetching exchange price')
                trans_date = get_datetime_or_none_from_string(
                    request.POST['trans_date'])
                trans_type = request.POST['trans_type']
                price = get_float_or_none_from_string(request.POST['price'])
                charges = get_float_or_zero_from_string(
                    request.POST['charges'])
                quantity = get_float_or_none_from_string(
                    request.POST['quantity'])
                chosen_currency = request.POST['currency']
                exchange_rate = get_conversion_rate(chosen_currency,
                                                    preferred_currency,
                                                    trans_date)
                broker = request.POST['broker']
                context = {
                    'users': users,
                    'operation': 'Update Transaction',
                    'conversion_rate': exchange_rate,
                    'curr_module_id': CryptoInterface.get_module_id(),
                    'trans_date': trans_date.strftime("%Y-%m-%d"),
                    'user': user,
                    'symbol': symbol,
                    'currencies': currencies,
                    'trans_type': trans_type,
                    'charges': charges,
                    'price': price,
                    'quantity': quantity,
                    'preferred_currency': preferred_currency,
                    'currency': chosen_currency,
                    'broker': broker,
                    'symbol': symbol
                }
                return render(request, template, context)
        context = {
            'users': users,
            'currencies': currencies,
            'operation': 'Update Transaction',
            'conversion_rate': trans.conversion_rate,
            'curr_module_id': CryptoInterface.get_module_id(),
            'preferred_currency': preferred_currency,
            'symbol': symbol,
            'user': user,
            'trans_date': trans.trans_date.strftime("%Y-%m-%d"),
            'trans_price': trans.trans_price,
            'price': trans.price,
            'quantity': trans.units,
            'broker': trans.broker,
            'notes': trans.notes,
            'charges': trans.fees,
            'currency': trans.buy_currency,
            'trans_type': trans.trans_type
        }
        print(f'view context: {context}')
        return render(request, template, context)
    except Crypto.DoesNotExist:
        return HttpResponseRedirect(reverse('crypto:crypto-list'))
Example #16
0
    def get_context_data(self, **kwargs):
        data = super().get_context_data(**kwargs)
        rsu = data['object']
        data['sell_trans'] = RSUSellTransactions.objects.filter(rsu_vest=rsu)
        data['curr_module_id'] = 'id_rsu_module'
        std = rsu.vest_date
        today = datetime.date.today()
        r = lambda: random.randint(0,255)
        color = '#{:02x}{:02x}{:02x}'.format(r(), r(), r())
        ret = list()
        ret.append({
            'label':'',
            'data': list(),
            'fill': 'false',
            'borderColor':color
        })
        ret[0]['data'].append({'x': rsu.vest_date.strftime('%Y-%m-%d'), 'y':round(float(rsu.shares_for_sale*rsu.aquisition_price*rsu.conversion_rate),2)})

        std = std+relativedelta(months=1)
        if std > today:
            std = today
        else:
            std = std.replace(day=1)
            
        while True:
            val = 0
            trans = list()
            trans.append(Trans(rsu.shares_for_sale, rsu.vest_date, 'buy', rsu.shares_for_sale*rsu.aquisition_price*rsu.conversion_rate))
            for st in RSUSellTransactions.objects.filter(rsu_vest=rsu, trans_date__lte=std):
                trans.append(Trans(st.units, st.trans_date, 'sell', st.trans_price))
            q, _,_,_,_ = reconcile_event_based(trans, list(), list())
            lv = get_historical_stock_price_based_on_symbol(rsu.award.symbol, rsu.award.exchange, std+relativedelta(days=-5), std)
            if lv:
                print(lv)
                conv_rate = 1
                if rsu.award.exchange == 'NASDAQ' or rsu.award.exchange == 'NYSE':
                    conv_val = get_conversion_rate('USD', 'INR', std)
                    if conv_val:
                        conv_rate = conv_val
                    for k,v in lv.items():
                        val += float(v)*float(conv_rate)*float(q)
                        break
            else:
                print(f'failed to get value of {rsu.award.exchange}:{rsu.award.symbol} on {std}')
            if val > 0:
                x = std.strftime('%Y-%m-%d')
                ret[0]['data'].append({'x': x, 'y':round(val,2)})
            if std == today:
                break   
            std = std+relativedelta(months=1)
            if std > today:
                std = today
        data['progress_data'] = ret
        try:
            s = Stock.objects.get(symbol=rsu.award.symbol, exchange=rsu.award.exchange)
            last_date = datetime.date.today()
            if rsu.unsold_shares == 0:
                all_sell = RSUSellTransactions.objects.filter(rsu_vest=rsu).order_by('trans_date')
                last_date = all_sell[len(all_sell)-1].trans_date

            res = get_comp_index_values(s, rsu.vest_date, last_date)
            if 'chart_labels' in res and len(res['chart_labels']) > 0:
                for k, v in res.items():
                    data[k] = v 
        except Stock.DoesNotExist:
            print(f'trying to get stock that does not exist {rsu.award.symbol} {rsu.award.exchange}')
        return data
Example #17
0
def espp_insights(request):
    template = 'espps/espp_insights.html'
    ret = list()
    today = datetime.date.today()
    total = dict()

    for i, espp in enumerate(Espp.objects.all()):
        std = espp.purchase_date
        r = lambda: random.randint(0, 255)
        color = '#{:02x}{:02x}{:02x}'.format(r(), r(), r())
        ret.append({
            'label': espp.purchase_date.strftime('%Y-%m-%d'),
            'data': list(),
            'fill': 'false',
            'borderColor': color
        })
        std = std + relativedelta(months=1)
        if std > today:
            std = today
        else:
            std = std.replace(day=1)
        reset_to_zero = False

        while True:
            val = 0
            trans = list()
            trans.append(
                Trans(espp.shares_purchased, espp.purchase_date, 'buy',
                      espp.total_purchase_price))
            for st in EsppSellTransactions.objects.filter(espp=espp,
                                                          trans_date__lte=std):
                trans.append(
                    Trans(st.units, st.trans_date, 'sell', st.trans_price))
            q, _, _, _, _ = reconcile_event_based(trans, list(), list())
            lv = get_historical_stock_price_based_on_symbol(
                espp.symbol, espp.exchange, std + relativedelta(days=-5), std)
            if lv:
                print(lv)
                conv_rate = 1
                if espp.exchange == 'NASDAQ' or espp.exchange == 'NYSE':
                    conv_val = get_conversion_rate('USD', 'INR', std)
                    if conv_val:
                        conv_rate = conv_val
                    for k, v in lv.items():
                        val += float(v) * float(conv_rate) * float(q)
                        break
                    else:
                        print(
                            f'failed to get value of {espp.exchange}:{espp.symbol} on {std}'
                        )
                if val > 0:
                    x = std.strftime('%Y-%m-%d')
                    ret[i]['data'].append({'x': x, 'y': round(val, 2)})
                    total[x] = total.get(x, 0) + round(val, 2)
                    reset_to_zero = True
                elif reset_to_zero:
                    x = std.strftime('%Y-%m-%d')
                    ret[i]['data'].append({'x': x, 'y': 0})
                    reset_to_zero = False
                    total[x] = total.get(x, 0)
                if std == today:
                    break
                std = std + relativedelta(months=1)
                if std > today:
                    std = today
    print(ret)
    if len(ret) > 0:
        d = list()
        for k, v in sorted(total.items()):
            d.append({'x': k, 'y': v})
        r = lambda: random.randint(0, 255)
        color = '#{:02x}{:02x}{:02x}'.format(r(), r(), r())
        ret.append({
            'label': 'total',
            'data': d,
            'fill': 'false',
            'borderColor': color,
            'spanGaps': 'false'
        })
    context = dict()
    context['progress_data'] = ret
    print(context)
    return render(request, template, context)
Example #18
0
    def get_context_data(self, **kwargs):
        data = super().get_context_data(**kwargs)
        print(data)
        data['goal_str'] = get_goal_name_from_id(data['object'].goal)
        data['user_str'] = get_user_name_from_id(data['object'].user)
        obj = data['object']
        cash_flows = list()
        cash_flows.append(
            (obj.purchase_date, -1 * float(obj.total_purchase_price)))
        for st in EsppSellTransactions.objects.filter(espp=data['object']):
            cash_flows.append((st.trans_date, float(st.trans_price)))
        if float(obj.latest_value) > 0:
            cash_flows.append((obj.as_on_date, float(obj.latest_value)))
        roi = xirr(cash_flows, 0.1) * 100
        roi = round(roi, 2)
        data['roi'] = roi
        data['curr_module_id'] = 'id_espp_module'
        '''
        data['transactions'] = list()
        for st in EsppSellTransactions.objects.filter(espp=data['object']):
            data['transactions'].append({
                'id':st.id,
                'trans_date':st.trans_date,
                'price':st.price,
                'units':st.units,
                'conversion_rate':st.conversion_rate,
                'trans_price':st.trans_price,
                'realised_gain':st.realised_gain,
                'notes':st.notes
            })
        '''
        std = obj.purchase_date
        today = datetime.date.today()
        r = lambda: random.randint(0, 255)
        color = '#{:02x}{:02x}{:02x}'.format(r(), r(), r())
        ret = list()
        ret.append({
            'label': '',
            'data': list(),
            'fill': 'false',
            'borderColor': color
        })
        ret[0]['data'].append({
            'x': obj.purchase_date.strftime('%Y-%m-%d'),
            'y': round(float(obj.total_purchase_price), 2)
        })
        std = std + relativedelta(months=1)
        if std > today:
            std = today
        else:
            std = std.replace(day=1)
        reset_to_zero = False
        while True:
            val = 0
            trans = list()
            trans.append(
                Trans(obj.shares_purchased, obj.purchase_date, 'buy',
                      obj.total_purchase_price))
            for st in EsppSellTransactions.objects.filter(espp=obj,
                                                          trans_date__lte=std):
                trans.append(
                    Trans(st.units, st.trans_date, 'sell', st.trans_price))
            q, _, _, _, _ = reconcile_event_based(trans, list(), list())
            lv = get_historical_stock_price_based_on_symbol(
                obj.symbol, obj.exchange, std + relativedelta(days=-5), std)
            if lv:
                print(lv)
                conv_rate = 1
                if obj.exchange == 'NASDAQ' or obj.exchange == 'NYSE':
                    conv_val = get_conversion_rate('USD', 'INR', std)
                    if conv_val:
                        conv_rate = conv_val
                    for k, v in lv.items():
                        val += float(v) * float(conv_rate) * float(q)
                        break
            else:
                print(
                    f'failed to get value of {obj.exchange}:{obj.symbol} on {std}'
                )
            if val > 0 or reset_to_zero:
                x = std.strftime('%Y-%m-%d')
                ret[0]['data'].append({'x': x, 'y': round(val, 2)})
                if val > 0:
                    reset_to_zero = True
                else:
                    reset_to_zero = False

            if std == today:
                break
            std = std + relativedelta(months=1)
            if std > today:
                std = today
        data['progress_data'] = ret
        try:
            s = Stock.objects.get(symbol=obj.symbol, exchange=obj.exchange)
            last_date = datetime.date.today()
            if obj.shares_avail_for_sale == 0:
                all_sell = EsppSellTransactions.objects.filter(
                    espp=obj).order_by('trans_date')
                last_date = all_sell[len(all_sell) - 1].trans_date

            res = get_comp_index_values(s, obj.purchase_date, last_date)
            if 'chart_labels' in res and len(res['chart_labels']) > 0:
                for k, v in res.items():
                    data[k] = v
        except Stock.DoesNotExist:
            print(
                f'trying to get stock that does not exist {obj.symbol} {obj.exchange}'
            )

        return data
Example #19
0
def rsu_insights(request):
    template = 'rsus/rsu_insights.html'
    ret = list()
    today = datetime.date.today()
    total = dict()
    
    for i, award in enumerate(RSUAward.objects.all()):
        rsus = RestrictedStockUnits.objects.filter(award=award)
        if len(rsus) > 0:
            std = award.award_date
            r = lambda: random.randint(0,255)
            color = '#{:02x}{:02x}{:02x}'.format(r(), r(), r())
            ret.append({
                'label':str(award.award_id),
                'data': list(),
                'fill': 'false',
                'borderColor':color
            })
            std = std.replace(day=1)
            reset_to_zero = False
            while True:
                val = 0
                for rsu in RestrictedStockUnits.objects.filter(award=award, vest_date__lte=std):
                    trans = list()
                    trans.append(Trans(rsu.shares_for_sale, rsu.vest_date, 'buy', rsu.shares_for_sale*rsu.aquisition_price))
                    for st in RSUSellTransactions.objects.filter(rsu_vest=rsu, trans_date__lte=std):
                        trans.append(Trans(st.units, st.trans_date, 'sell', st.trans_price))
                    q, _,_,_,_ = reconcile_event_based(trans, list(), list())
                    lv = get_historical_stock_price_based_on_symbol(award.symbol, award.exchange, std+relativedelta(days=-5), std)
                    if lv:
                        print(lv)
                        conv_rate = 1
                        if award.exchange == 'NASDAQ' or award.exchange == 'NYSE':
                            conv_val = get_conversion_rate('USD', 'INR', std)
                            if conv_val:
                                conv_rate = conv_val
                            for k,v in lv.items():
                                val += float(v)*float(conv_rate)*float(q)
                                break
                    else:
                        print(f'failed to get value of {award.award_id} {award.exchange}:{award.symbol} on {std}')
                if val > 0:
                    x = std.strftime('%Y-%m-%d')
                    ret[i]['data'].append({'x': x, 'y':round(val,2)})
                    total[x] = total.get(x, 0) + round(val,2)
                    reset_to_zero = True
                elif reset_to_zero:
                    x = std.strftime('%Y-%m-%d')
                    ret[i]['data'].append({'x': x, 'y':0})
                    reset_to_zero = False
                    total[x] = total.get(x, 0)
                if std == today:
                    break
                std = std+relativedelta(months=1)
                if std > today:
                    std = today
    print(ret)
    if len(ret) > 0:
        d = list()
        for k,v in sorted(total.items()):
            d.append({'x':k, 'y':round(v, 2)})
        r = lambda: random.randint(0,255)
        color = '#{:02x}{:02x}{:02x}'.format(r(), r(), r())
        ret.append({
                    'label':'total',
                    'data': d,
                    'fill': 'false',
                    'borderColor':color
                })
    context = dict()
    context['progress_data'] = ret
    return render(request, template, context)
Example #20
0
def add_transaction(request):
    template = 'crypto/add_transaction.html'
    currencies = supported_currencies_as_list()
    users = get_all_users()
    preferred_currency = get_preferred_currency()
    if request.method == 'POST':
        if "submit" in request.POST:
            symbol = request.POST['symbol']
            user = request.POST['user']
            print('user is of type:', type(user))
            trans_date = get_datetime_or_none_from_string(
                request.POST['trans_date'])
            trans_type = request.POST['trans_type']
            price = get_float_or_none_from_string(request.POST['price'])
            quantity = get_float_or_none_from_string(request.POST['quantity'])
            conversion_rate = get_float_or_none_from_string(
                request.POST['conversion_rate'])
            trans_price = get_float_or_none_from_string(
                request.POST['trans_price'])
            broker = request.POST['broker']
            notes = request.POST['notes']
            chosen_currency = request.POST['currency']
            charges = get_float_or_zero_from_string(request.POST['charges'])
            insert_trans_entry(symbol, user, trans_type, quantity, price,
                               trans_date, notes, broker, conversion_rate,
                               charges, chosen_currency, trans_price)
            update_crypto_for_user(user)
        else:
            print('fetching exchange price')
            symbol = request.POST['symbol']
            user = request.POST['user']
            trans_date = get_datetime_or_none_from_string(
                request.POST['trans_date'])
            trans_type = request.POST['trans_type']
            price = get_float_or_none_from_string(request.POST['price'])
            charges = get_float_or_zero_from_string(request.POST['charges'])
            quantity = get_float_or_none_from_string(request.POST['quantity'])
            chosen_currency = request.POST['currency']
            exchange_rate = get_conversion_rate(chosen_currency,
                                                preferred_currency, trans_date)
            broker = request.POST['broker']
            coins = get_crypto_coins()
            context = {
                'users': users,
                'operation': 'Add Transaction',
                'conversion_rate': exchange_rate,
                'curr_module_id': CryptoInterface.get_module_id(),
                'trans_date': trans_date.strftime("%Y-%m-%d"),
                'user': user,
                'symbol': symbol,
                'currencies': currencies,
                'trans_type': trans_type,
                'charges': charges,
                'price': price,
                'quantity': quantity,
                'preferred_currency': preferred_currency,
                'currency': chosen_currency,
                'broker': broker,
                'coins': coins
            }
            return render(request, template, context)
    coins = get_crypto_coins()
    context = {
        'users': users,
        'currencies': currencies,
        'operation': 'Add Transaction',
        'conversion_rate': 1,
        'curr_module_id': CryptoInterface.get_module_id(),
        'preferred_currency': preferred_currency,
        'coins': coins
    }
    print(f'view context: {context}')
    return render(request, template, context)