示例#1
0
文件: views.py 项目: pgwthf/TSB
def show_metasystem(request, metasystem_id):
    '''
    Show MetaSystem with <metasystem_id> along with it
    '''
    notify = None

    if request.method == 'POST' and request.POST.get('action'):
        system_list = request.POST.getlist('id')

        if request.POST.get('action') == 'Delete':
            if not len(system_list):
                notify = Notify('Delete failed, select System(s) to delete')
            else:
                notify = Notify('Delete System(s) {}?'.format(', '.join(
                        system_list)))
                notify.set_replies(request, ('Yes', 'No'))
                request.session['system_delete_list'] = system_list

    elif request.method == 'POST' and request.POST.get('reply'):
        system_list = request.session.get('system_delete_list')
        if not system_list:
            raise AttributeError('session has no valid system_delete_list')
        del request.session['system_delete_list']
        if request.POST.get('reply') == 'Yes':
            for system_id in system_list:
                system = System.objects.get(id=system_id)
                system.delete()
            notify = Notify('System(s) {} deleted'.format(','.join(
                    system_list)))
        elif request.POST.get('reply') == 'No':
            notify = Notify('Delete cancelled')

    metasystem = MetaSystem.objects.get(id=metasystem_id)

    if request.method == 'POST' and request.POST.get('action'):

        if request.POST.get('action') == 'Start calculations':
            errors = metasystem.set_active()
            if errors:
                notify = Notify('MetaSystem NOT started: {}'.format(', '.join(
                        errors)))
            else:
                notify = Notify('MetaSystem {} started'.format(metasystem.name))

        elif request.POST.get('action') == 'Stop calculations':
            metasystem.set_inactive()
            notify = Notify('MetaSystem {} stopped'.format(metasystem.name))

    values = metasystem.get_system_summary(('reliability', 'profit_factor',
            'exp_p_day', 'profit_pa', 'ann_profit', 'min_year', 'min_dd_ratio',
            'sqn'))
    if values:
        performance = []
        for key, fmt in OUTPUT_FORMATS.items(): # to maintain order
            value = values.get(key, None)
            if value is not None:
                performance.append((fmt['name'], fmt['format'].format(value)))
    else:
        performance = None 

    metasystem.build_structure()

    # copy system to method if required
    if request.method == 'POST' and request.POST.get('copy'):
        copyform = CopyForm(data=request.POST)
        if copyform.is_valid():
            new_ms_id = copyform.cleaned_data['metasystem']
            reverse = copyform.cleaned_data['reverse']
            for method in metasystem.method_set.all():
                method.copy(new_ms_id, reverse=reverse, 
                        comment='copy from metasystem {}'.format(metasystem.id))
            notify = Notify('{} methods copied to metasystem {}'.format(
                    metasystem.method_set.count(), metasystem.id))
    else:
        copyform = CopyForm()

    systems = System.objects.filter(metasystem__id=metasystem_id)

    view_settings = {
            'parameters': True,
            'performance': True,
            'result': True
            }

    systems_table = MakeSystemsTable(data=systems, order_by=('-id',), 
            show=view_settings, excludes=['metasystem'])

    # generate column_titles
    if systems.count():
        systems_table.base_columns['params'].verbose_name = mark_safe(
                        '</th><th>'.join(str2dict_keys(systems[0].params)))
        for key, params in OUTPUT_FORMATS.items():
            if 'title' in params:
                systems_table.base_columns[key].verbose_name = params['title']
    RequestConfig(request, paginate={'per_page': 100}).configure(systems_table)


    return render(request, 'show_metasystem.html', {
            'metasystem': metasystem,
            'copyform': copyform,
            'notify': notify,
            'performance': performance,
            'systems_table': systems_table, 
#            'filterformset': filterformset,
#            'bookmarkform': bookmarkform,

            })
示例#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,
            })