Esempio n. 1
0
def addCashTransaction(request, portfolio_id):
    if not request.POST:
        form = CashTransactionForm()
        return render_to_response('manager/addCashTransaction.html', {'form':form, 'p_id':portfolio_id},context_instance=RequestContext(request))
    
    ajax_return = {}
    
    newCashTransaction = CashTransactionForm(request.POST)
    success = False
    if newCashTransaction.is_valid():
        try:
            newCash = newCashTransaction.save(commit=False)
            newCash.portfolio = Portfolio.objects.get(pk=portfolio_id)
            newCash.security, created = Security.objects.get_or_create(symbol="CASH")
            newCash.units = newCash.amount
            newCash.amount = newCash.amount * 100
            newCash.unit_price = 100
            newCash.save()
            # update holding.
            count = PortfolioHolding.objects.filter(portfolio=newCash.portfolio, securities=newCash.security).count()
            if count == 0:
                ph = PortfolioHolding(portfolio=newCash.portfolio, securities=newCash.security, held=0, average_price=100, last_price=100)
            else:
                ph = PortfolioHolding.objects.get(portfolio=newCash.portfolio, securities=newCash.security)

            ph.updateHolding(newCash)
            ph.save()
                        
            success = True
            msg = u"Added new transaction. %s $ %f to portfolio!" %( newCash.type.name, newCash.units )
            ajax_return['msg'] = msg
            ajax_return['ok'] = success
        except:
            success = False;
            ajax_return['msg'] = u"Cannot add transaction."
            ajax_return['ok'] = success
    else:
        ajax_return['msg'] = u"Required Fields Missing."
            
    if request.is_ajax():
        serialized = simplejson.dumps(ajax_return)
        if success == True:
            return HttpResponse(serialized, mimetype="application/json")
        else:
            return HttpResponseServerError(serialized, mimetype="application/json")
    else:
        if success == True:
            return HttpResponseRedirect('/tracker/portfolios/'+portfolio_id)
        else:
            return render_to_response('manager/addCashTransaction.html', {'form':newCashTransaction,'p_id':portfolio_id},context_instance=RequestContext(request))
Esempio n. 2
0
def update_cash_holding(portfolio, amount):
    """
    update cash holdings after security buy/sell
    """
    #print "updating portfolioholding with amount:", amount
    # amount in cents. need to store $.
    amount = dollarize(amount)
    print 'amount to update in $:', amount
    cash_obj, created = Security.objects.get_or_create(symbol='CASH')
    try:
        cash_holding = PortfolioHolding.objects.get(portfolio=portfolio,
                        security=cash_obj)
        print 'held' + str(cash_holding.held)
        print 'add' + str(amount)
        print 'new held' + str(cash_holding.held + amount)
        cash_holding.held = cash_holding.held + amount
        print 'cash_holding.held', cash_holding.held
        cash_holding.save()
        
    except PortfolioHolding.DoesNotExist:
        print 'cash holding does not exists.'
        new_holding = PortfolioHolding()
        new_holding.portfolio = portfolio
        new_holding.security = cash_obj
        new_holding.held = amount
        new_holding.average_price = 1
        new_holding.last_price = 1
        new_holding.save()
Esempio n. 3
0
def editCashTransaction(request, transaction_id=None):
    transaction = None
    portfolio_id = request.session.get('p_id')
    old_transaction_amount = None
    # get object if id provided.    
    if transaction_id is not None:
        transaction = get_object_or_404(Transaction, pk=transaction_id)
        #display in dollars.
        old_transaction_amount = transaction.amount
        transaction.amount = transaction.amount / 100
        
    # POST -> coming from form. either update or new.
    if request.method == 'POST':
        new_transaction_form = CashTransactionForm(request.POST, instance=transaction)
        if new_transaction_form.is_valid():
            new_transaction = new_transaction_form.save(commit = False)
            new_transaction.portfolio = Portfolio.objects.get(pk=portfolio_id)
            new_transaction.security, created = Security.objects.get_or_create(symbol="CASH")
            new_transaction.units = new_transaction.amount
            new_transaction.amount = new_transaction.amount * 100 # store in cents.
            new_transaction.unit_price = 100 #100 cents. 1$
            new_transaction.save()
            
            # update holding only if amount has changed.
            if old_transaction_amount != new_transaction.amount:
                count = PortfolioHolding.objects.filter(portfolio=new_transaction.portfolio, security=new_transaction.security).count()
                if count == 0:
                    ph = PortfolioHolding(portfolio=new_transaction.portfolio, held=0, average_price=100, last_price=100)
                else:
                    ph = PortfolioHolding.objects.get(portfolio=new_transaction.portfolio)

                ph.updateHolding(new_transaction)
                ph.save()
                # only now can add security.
                # ph.securities.add(new_transaction.security)
            return HttpResponseRedirect('/tracker/portfolios/'+portfolio_id)
    else:
        form = CashTransactionForm(instance = transaction)
    return render_to_response('manager/addCashTransaction.html', {'form':form, 'p_id':portfolio_id}, context_instance=RequestContext(request))
Esempio n. 4
0
def update_holdings(portfolio, security):
    """
    takes portfolio and security and updates for that security.
    add to held if not present
    update security holding if held.
    """
    holding = None
    try:
        holding = PortfolioHolding.objects.get(portfolio=portfolio, security=security)
    except PortfolioHolding.DoesNotExist:
        # no holdings row exists for this security.
        new_holding = PortfolioHolding()
        new_holding.portfolio = portfolio
        new_holding.security = security
        new_holding.held = 0
        new_holding.average_price = 0
        new_holding.last_price = 0
        new_holding.save()
        holding = new_holding
        
    transactions = Transaction.objects.all().filter(portfolio=portfolio, security=security)
    held = 0;
    if security.symbol == 'CASH':
        for tran in transactions:
            if tran.type.name == 'Deposit':
                held = held + tran.amount
            elif tran.type.name == 'Withdraw':
                held = held - tran.amount
        
        print 'found it: ', held
        held = held / 100.00
        print 'after: ', held
    else:
        for tran in transactions:
            if tran.type.name == 'Buy':
                held = held + tran.units
            elif tran.type.name == 'Sell':
                held = held - tran.units
    
    holding.held = str(held)
    holding.save()    
Esempio n. 5
0
def addSecurityTransaction(request, portfolio_id):
    # add new security
    # update average price.
    BUYING = True
    if not request.POST:
        form = SecurityTransactionForm()
        return render_to_response('manager/addSecurityTransaction.html', {'form':form, 'p_id':portfolio_id},context_instance=RequestContext(request))
    
    ajax_return = {}
    success = False
    
    newForm = SecurityTransactionForm(request.POST)
    if newForm.is_valid():
        try:
            portfolio = Portfolio.objects.get(pk=portfolio_id)
            newSecurity = newForm.save(commit=False)

            if newSecurity.type.name == "Sell":
                BUYING = False
            
            symbol = string.upper(newForm.cleaned_data['symbol'])
            securityObj, created = Security.objects.get_or_create(symbol=symbol)
            newSecurity.portfolio = portfolio
            newSecurity.security = securityObj
            newSecurity.unit_price = newSecurity.centicize(newSecurity.unit_price)
            newSecurity.amount = newSecurity.units * newSecurity.unit_price
            newSecurity.commission = newSecurity.centicize(newSecurity.commission)
            
            if newSecurity.commission > 0:
                if BUYING:
                    newSecurity.amount += newSecurity.commission
                else:
                    newSecurity.amount -= newSecurity.commission
            
            newSecurity.save()
            
            # update holding.
            count = PortfolioHolding.objects.filter(portfolio=portfolio, securities=newSecurity.security).count()
            if count == 0:
                ph = PortfolioHolding(portfolio=portfolio, securities=securityObj, held=newSecurity.units, average_price=newSecurity.unit_price, last_price=newSecurity.unit_price)
                print 'created new ph'
            else:
                ph = PortfolioHolding.objects.get(portfolio=portfolio, securities=newSecurity.security)
                #ph.updateHolding(newSecurity)
            ph.save()
            
            # update cash
            cash_obj, created = Security.objects.get_or_create(symbol='CASH')
            c_count = PortfolioHolding.objects.filter(portfolio=portfolio, securities=cash_obj).count()
            if c_count == 0:
                ch = PortfolioHolding()
                ch.portfolio = portfolio
                ch.securities = cash_obj
                ch.average_price = 100
                ch.last_price = 100
                if BUYING:
                    ch.held = -newSecurity.amount
            else:
                ch = PortfolioHolding.objects.get(portfolio=portfolio, securities=cash_obj)
                print 'previously held:', ch.held
                if BUYING:
                    ch.held -= newSecurity.amount
                    print 'after buying:', newSecurity.amount, ": ", ch.held
                else:
                    ch.held += newSecurity.amount
                    print 'after selling:', newSecurity.amount, ": ", ch.held

            ch.save()
            success = True
            msg = u"Added new transaction. %s %d shares of %s!" %( newSecurity.type.name, newSecurity.units, newSecurity.security.symbol)
            ajax_return['ok'] = success
            ajax_return['msg'] = msg
        except:
            success = False;
            ajax_return['msg'] = u"Cannot add transaction."
            ajax_return['ok'] = success
    else:
        ajax_return['msg'] = u"Required Fields Missing."
        
    if request.is_ajax():
        serialized = simplejson.dumps(ajax_return)
        if success:
            return HttpResponse(serialized, mimetype="application/json")
        else:
            return HttpResponseServerError(serialized, mimetype="application/json")
    else:
        if success:
            print "success..."
            return HttpResponseRedirect('/tracker/portfolios/'+portfolio_id)
        else:
            print "failed..."
            return render_to_response('manager/addSecurityTransaction.html', {'form':newForm,'p_id':portfolio_id}, context_instance=RequestContext(request))
Esempio n. 6
0
def editSecurityTransaction(request, transaction_id=None):
    transaction = None
    portfolio_id = request.session.get('p_id')
    BUYING = True
    # get object if id provided.    
    if transaction_id is not None:
        transaction = get_object_or_404(Transaction, pk=transaction_id)
        # share price in dollars.
        transaction.unit_price = transaction.dollarize(transaction.unit_price)
        transaction.commission = transaction.dollarize(transaction.commission)
        transaction.symbol = transaction.security.symbol
        # commission in dollars.
        
    if request.method == 'POST':
        # form submitted.
        new_transaction_form = SecurityTransactionForm(request.POST, instance=transaction)
        if new_transaction_form.is_valid():
            if newSecurity.type.name == "Sell":
                BUYING = False            
            
            new_transaction = new_transaction_form.save(commit=False)
            new_transaction.portfolio = Portfolio.objects.get(pk=portfolio_id)
            
            securityObj, created = Security.objects.get_or_create(symbol=symbol)
            new_transaction.portfolio = portfolio
            new_transaction.security = securityObj
            new_transaction.unit_price = new_transaction.centicize(new_transaction.unit_price)
            new_transaction.amount = new_transaction.units * new_transaction.unit_price
            new_transaction.commission = new_transaction.centicize(new_transaction.commission)
            
            if new_transaction.commission > 0:
                if BUYING:
                    new_transaction.amount += new_transaction.commission
                else:
                    new_transaction.amount -= new_transaction.commission
            
            new_transaction.save()
            
            # update holding.
            count = PortfolioHolding.objects.filter(portfolio=portfolio, securities=new_transaction.security).count()
            if count == 0:
                ph = PortfolioHolding(portfolio=portfolio, securities=securityObj, held=new_transaction.units, average_price=new_transaction.unit_price, last_price=new_transaction.unit_price)
                print 'created new ph'
            else:
                ph = PortfolioHolding.objects.get(portfolio=portfolio, securities=new_transaction.security)
                #ph.updateHolding(newSecurity)
            ph.save()
            
            # update cash
            cash_obj, created = Security.objects.get_or_create(symbol='CASH')
            c_count = PortfolioHolding.objects.filter(portfolio=portfolio, securities=cash_obj).count()
            if c_count == 0:
                ch = PortfolioHolding()
                ch.portfolio = portfolio
                ch.securities = cash_obj
                ch.average_price = 100
                ch.last_price = 100
                if BUYING:
                    ch.held = -new_transaction.amount
            else:
                ch = PortfolioHolding.objects.get(portfolio=portfolio, securities=cash_obj)
                print 'previously held:', ch.held
                if BUYING:
                    ch.held -= new_transaction.amount
                    print 'after buying:', new_transaction.amount, ": ", ch.held
                else:
                    ch.held += new_transaction.amount
                    print 'after selling:', new_transaction.amount, ": ", ch.held

            ch.save()
            return HttpResponseRedirect('/tracker/portfolios/'+portfolio_id)
    else:
        #empty form        
        if transaction is None:
            form = SecurityTransactionForm(instance=transaction)
        else:
            form = SecurityTransactionForm(symbol=transaction.symbol, instance=transaction)
                               
    return render_to_response('manager/addSecurityTransaction.html', {'form':form, 'p_id':portfolio_id},context_instance=RequestContext(request))