예제 #1
0
파일: views.py 프로젝트: pgwthf/TSB
def edit_system(request, system_id=None):
    '''
    Show System with <system_id>
    '''
    message = ''
    system = System.objects.get(id=system_id)

    # generate performance list
    performance = []
    results = []
    for param, fmt in OUTPUT_FORMATS.items():
        value = getattr(system, param, None)
        if fmt['type'] == 'performance' and value is not None: # 0 is allowed!
            performance.append((fmt['name'], fmt['format'].format(value)))
            results.append((fmt['name'], fmt['format'].format(value)))

    #generate equity table
    equity = EquityHistory(system_id=system.id)
    if equity.exists():
        total_equity = equity.get('year')
        equity_table = EquityTable(total_equity, order_by=('date',))
        RequestConfig(request, paginate=None).configure(equity_table)
    else:
        equity_table = None
    #/equity table

    #generate portfolio table
    trades = Trade.objects.filter(system=system, rule_exit=None)
    if len(trades):
        latest_date = trades[0].stock.get_latest_date()
        stoploss_date = next_weekday(latest_date)
    else:
        stoploss_date = None
    portfolio_table = PortfolioTable(trades, order_by=('date_entry',))
    RequestConfig(request, paginate=None).configure(portfolio_table)

    #generate trades table
    trades = Trade.objects.filter(system=system, rule_exit__isnull=False)
    trades_table = TradesTable(trades, exclude=('id', 'system'),
                                                    order_by=('date_entry',))
    RequestConfig(request, paginate=None).configure(trades_table)
    #/trades table

    # copy system to method if required
    if request.method == 'POST':
        if request.POST.get('todo') == 'Delete trade':
            trade_list = request.POST.getlist('tradeid')
            Trade.objects.filter(id__in=trade_list).delete()
            tradeform = TradeForm()
        else:
            tradeform = TradeForm(data=request.POST)
            if tradeform.is_valid():
                name = tradeform.cleaned_data.get('symbol').upper()
                volume = tradeform.cleaned_data.get('volume')
                price = tradeform.cleaned_data.get('price')
                date = tradeform.cleaned_data.get('date')
                method = system.metasystem.method_set.all()[0]
                if request.POST.get('todo') == 'Enter position': 
                    if not volume:
                        message = 'volume must be specified for entry'
                    else: 
                        try:
                            stock = Stock.objects.get(name=name)
                            print 'NAME', stock.name
                            trade = Trade(system=system, stock=stock,
                                    method=method, rule_entry='discret.',
                                    price_entry=price, date_entry=date,
                                    volume=volume)
                            trade.save()
                            message = 'Position entered'
                        except:
                            message = 'Failed to enter position'
                elif request.POST.get('todo') == 'Exit position':
                    position_list = request.POST.getlist('positionid')
                    if len(position_list) != 1:
                        message = 'One position must be selected to exit'
                    else:
                        position_id = position_list[0]
                        stock = Trade.objects.get(id=position_id).stock
                        try:
                            trade = Trade.objects.get(id=position_id,
                                    system=system, stock=stock, method=method, 
                                    rule_entry='discret.', rule_exit=None)
                            trade.rule_exit = 'discret.'
                            trade.price_exit = price
                            trade.date_exit = date
                            trade.save()
                            message = 'Position exited'
                        except:
                            message = 'Failed to exit position'

    else: # this is the first page load
        tradeform = TradeForm()


    return render(request, 'edit_system.html', 
            {'system': system,
            'trades_table': trades_table,
            'stoploss_date': stoploss_date,
            'equity_table': equity_table,
            'portfolio_table': portfolio_table,
            'tradeform': tradeform,
            'performance': performance,
            'result': results,
            'message': message })
예제 #2
0
파일: views.py 프로젝트: pgwthf/TSB
def show_system(request, system_id=None):
    '''
    Show System with <system_id>
    '''
    notify = None

    system = System.objects.get(id=system_id)
    metasystem = system.metasystem
    metasystem.make_system(system.params)

    # generate performance list
    performance = []
    results = []
    for param, fmt in OUTPUT_FORMATS.items():
        value = getattr(system, param, None)
        if fmt['type'] == 'performance' and value is not None: # 0 is allowed!
            performance.append((fmt['name'], fmt['format'].format(value)))
        if fmt['type'] == 'result' and value is not None:
            results.append((fmt['name'], fmt['format'].format(value)))

    #generate equity table
    equity = EquityHistory(system_id=system.id)
    if equity.exists():
        total_equity = equity.get('year')
        equity_table = EquityTable(total_equity, order_by=('date',))
        RequestConfig(request, paginate=None).configure(equity_table)
    else:
        equity_table = None
    #/equity table

    # copy system to method if required
    if request.method == 'POST':
        copyform = CopyForm(data=request.POST)
        if request.POST.get('action') == 'Copy System' and copyform.is_valid():
            new_ms_id = copyform.cleaned_data['metasystem']
            reverse = copyform.cleaned_data['reverse']
            for method in metasystem.method_set.all():
                parameters = system.get_params(method)
                method.copy(new_ms_id, parameters, reverse=reverse,
                        comment='copy from system {}'.format(system.id))
    else:
        copyform = CopyForm()

    # bookmark system if required
    if request.method == 'POST':
        bookmarkform = BookmarkForm(data=request.POST)
        if request.POST.get('action') == 'Bookmark Selected':
            process_bookmarkform(bookmarkform, request.POST, [system_id])
    elif system.bookmark:
        bookmarkform = BookmarkForm(initial={'bookmark': system.bookmark.id})
    else:
        bookmarkform = BookmarkForm()

    # process trades/positions
    tradeform = TradeForm()
    if request.method == 'POST':
        if request.POST.get('action') in ('Delete trade', 'Delete position'):
            trade_list = request.POST.getlist('tradeid')
            trades = ','.join(Trade.objects.get(id=t).stock.name for t in 
                    trade_list)
            if not len(trade_list):
                notify = Notify('Delete failed, select position to delete')
            else:
                notify = Notify('Delete Trade(s) {}?'.format(trades))
                notify.set_replies(request, ('Yes', 'No'))
                request.session['trade_delete_list'] = trade_list

        elif request.POST.get('reply'):
            trade_list = request.session.get('trade_delete_list')
            if not trade_list:
                raise AttributeError('session has no valid trade_delete_list')
            del request.session['trade_delete_list']
            if request.POST.get('reply') == 'Yes':
                trades = ','.join(Trade.objects.get(id=t).stock.name for t in 
                        trade_list)
                Trade.objects.filter(id__in=trade_list).delete()
                notify = Notify('Trade(s) {} deleted'.format(trades))
            elif request.POST.get('reply') == 'No':
                notify = Notify('Delete cancelled')

        else:
            tradeform = TradeForm(data=request.POST)
            if tradeform.is_valid():
                name = tradeform.cleaned_data.get('symbol').upper()
                volume = tradeform.cleaned_data.get('volume')
                price = tradeform.cleaned_data.get('price')
                date = tradeform.cleaned_data.get('date')
                method = system.metasystem.method_set.all()[0]
                if request.POST.get('action') == 'Enter position': 
                    if not volume:
                        notify = Notify('volume must be specified for entry')
                    else: 
                        try:
                            stock = Stock.objects.get(name=name)
                            print 'NAME', stock.name
                            trade = Trade(system=system, stock=stock,
                                    method=method, rule_entry='discret.',
                                    price_entry=price, date_entry=date,
                                    volume=volume)
                            trade.save()
                            notify = Notify('Position entered')
                        except:
                            notify = Notify('Failed to enter position')
                elif request.POST.get('action') == 'Exit position':
                    position_list = request.POST.getlist('positionid')
                    if len(position_list) != 1:
                        notify = Notify('One position must be selected to exit')
                    else:
                        position_id = position_list[0]
                        stock = Trade.objects.get(id=position_id).stock
                        try:
                            trade = Trade.objects.get(id=position_id,
                                    system=system, stock=stock, method=method, 
                                    rule_entry='discret.', rule_exit=None)
                            trade.rule_exit = 'discret.'
                            trade.price_exit = price
                            trade.date_exit = date
                            trade.save()
                            notify = Notify('Position exited')
                        except:
                            notify = Notify('Failed to exit position')

    else: # this is the first page load
        tradeform = TradeForm()

    #generate portfolio table
    trades = Trade.objects.filter(system=system, rule_exit=None)
    if len(trades):
        latest_date = trades[0].stock.get_latest_date()
        stoploss_date = next_weekday(latest_date)
    else:
        stoploss_date = None
    portfolio_table = PortfolioTable(trades, order_by=('date_entry',))
    RequestConfig(request, paginate=None).configure(portfolio_table)

    #generate trades table
    trades = Trade.objects.filter(system=system).exclude(rule_exit=None)
    trades_table = TradesTable(trades, order_by=('date_entry',))
    RequestConfig(request, paginate=None).configure(trades_table)
    #/trades table


    return render(request, 'show_system.html', {
            'metasystem': metasystem,
            'system': system,
            'trades_table': trades_table,
            'equity_table': equity_table,
            'performance': performance,
            'result': results,
            'copyform': copyform,
            'bookmarkform': bookmarkform,
            'portfolio_table': portfolio_table,
            'stoploss_date': stoploss_date,
            'tradeform': tradeform,
            'notify': notify,
            })