def show_pools(request): ''' Show overview of all pools in the Pools database. ''' notify = None if request.method == 'POST' and request.POST.get('action'): pool_list = request.POST.getlist('id') if request.POST.get('action') == 'Copy': if not len(pool_list): notify = Notify('Copy failed, select a pool to copy') elif len(pool_list) > 1: notify = Notify('Copy failed, select only one pool to copy') else: for pool_id in pool_list: # NOTE: only pool_list[0] is used! pool = Pool.objects.get(id=pool_id) name = pool.name new_pool = pool.copy() notify = Notify('Pool "{}" copied to "{}"'.format(name, new_pool.name)) elif request.POST.get('action') == 'Delete': if not len(pool_list): notify = Notify('Delete failed, select pool(s) to delete') else: notify = Notify('Delete pool(s) {}?'.format(', '.join( pool_list))) notify.set_replies(request, ('Yes', 'No')) request.session['pool_delete_list'] = pool_list elif request.method == 'POST' and request.POST.get('reply'): pool_list = request.session.get('pool_delete_list') if not pool_list: raise AttributeError('session has no valid pool_delete_list') del request.session['pool_delete_list'] if request.POST.get('reply') == 'Yes': Pool.objects.filter(pk__in=pool_list).delete() notify = Notify('Pool(s) {} deleted'.format(','.join(pool_list))) elif request.POST.get('reply') == 'No': notify = Notify('Delete cancelled') elif request.method == 'POST' and request.POST.get('upload'): upload_file = request.FILES['poolfile'] pool_name, unused = '{}'.format(upload_file).split('.', 1) startdate = datetime.date(2012,1,1) currency = Stock.US_DOLLAR index_name = '^GSPC' index = Stock.objects.get(name=index_name) pool, unused = Pool.objects.get_or_create(name=pool_name, index=index, startdate=startdate) pool.import_csv(upload_file, index_name, currency) pools = Pool.objects.all() pools_table = PoolsTable(pools, order_by=('-id',)) RequestConfig(request, paginate={'per_page': 100}).configure(pools_table) return render(request, 'show_pools.html', { 'pools_table': pools_table, 'notify': notify, })
def show_metasystems(request, group_id=None): ''' Show overview of all (meta)systems in the (Meta)Systems database. ''' notify = None if request.method == 'POST' and request.POST.get('action'): metasystem_list = request.POST.getlist('id') if request.POST.get('action') == 'Copy': if not len(metasystem_list): notify = Notify('Copy failed, select a MetaSystem to copy') elif len(metasystem_list) > 1: notify = Notify('Copy failed, select only one MetaSystem to '\ 'copy') else: for metasystem_id in metasystem_list: metasystem = MetaSystem.objects.get(id=metasystem_id) new_metasystem = metasystem.copy() name = new_metasystem.name notify = Notify('MetaSystem "{}" copied to "{}"'.format(name, new_metasystem.name)) elif request.POST.get('action') == 'Delete': if not len(metasystem_list): notify = Notify('Delete failed, select MetaSystem(s) to delete') else: notify = Notify('Delete MetaSystem(s) {}?'.format(', '.join( metasystem_list))) notify.set_replies(request, ('Yes', 'No')) request.session['metasystem_delete_list'] = metasystem_list elif request.method == 'POST' and request.POST.get('reply'): metasystem_list = request.session.get('metasystem_delete_list') if not metasystem_list: raise AttributeError('session has no valid metasystem_delete_list') del request.session['metasystem_delete_list'] if request.POST.get('reply') == 'Yes': MetaSystem.objects.get(id__in=metasystem_list).delete() # for metasystem_id in metasystem_list: # metasystem = MetaSystem.objects.get(id=metasystem_id) # metasystem.delete() notify = Notify('MetaSystem(s) {} deleted'.format(','.join( metasystem_list))) elif request.POST.get('reply') == 'No': notify = Notify('Delete cancelled') if group_id: group = Group.objects.get(id=group_id) metasystems = MetaSystem.objects.filter(group=group) exclude = ('group') else: metasystems = MetaSystem.objects.all() group = None exclude = () rs = None keys = ('reliability', 'profit_factor', 'exp_p_day', 'profit_pa', 'ann_profit', 'min_year', 'min_dd_ratio', 'sqn') metasystems_table = MakeMetaSystemsTable(rs, keys, data=metasystems, order_by=('-id',),exclude=exclude) # generate titles for performance columns: titles = [] for key, params in OUTPUT_FORMATS.items(): if key in keys: if 'title' in params: key = params['title'] else: key = key.replace('_', ' ') titles.append(key) metasystems_table.base_columns['performance'].verbose_name = mark_safe( '</th><th>'.join(titles)) RequestConfig(request, paginate=None).configure(metasystems_table) return render(request, 'show_metasystems.html', { 'metasystems_table': metasystems_table, 'group': group, 'notify': notify, 'groups': Group.objects.all(), })
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, })
def show_pool(request, pool_id=None): ''' Show contents of pool <pool_id>. ''' notify = None splits = None missing_prices = None missing_channels = None pool = None if pool_id == 'new' else Pool.objects.get(id=pool_id) if request.method == 'POST' and request.POST.get('action'): daterangeform = DateRangeForm(request.POST) if not daterangeform.is_valid(): notify = Notify('Invalid date(s)') else: startdate = daterangeform.cleaned_data['fromdate'] enddate = daterangeform.cleaned_data['todate'] if request.POST.get('action') == 'Download latest prices': # dl_latest_prices(pool) pool.download_latest_prices() elif request.POST.get('action') == 'Download index': pool.index.download_history(startdate, enddate) elif request.POST.get('action') == 'Calculate index channels': Channel.calculate(pool.index, startdate, enddate) elif request.POST.get('action') == 'Download all stock prices': #CONSIDER: run separate process? # dl_prices(pool, startdate, enddate) pool.download_prices(startdate, enddate) elif request.POST.get('action') == 'Check for missing prices': missing_prices = pool.missing_prices(startdate, enddate) elif request.POST.get('action') == 'Check for stock splits': splits = pool.check_splits() elif request.POST.get('action') == 'Check for missing channels': missing_channels = pool.missing_channels(startdate, enddate) elif request.POST.get('action') == 'Calculate all stock channels': pool.calculate_channels(startdate, enddate) elif pool: enddate = datetime.date.today() if not pool.enddate else pool.enddate daterangeform = DateRangeForm(initial={ 'fromdate':pool.startdate, 'todate': enddate}) else: daterangeform = None if request.method == 'POST' and request.POST.get('save'): poolform = PoolForm(request.POST, instance=pool) memberform = MemberForm(request.POST, prefix='stock') if poolform.is_valid(): pool = poolform.save() if memberform.is_valid(): obj = memberform.save(commit=False) obj.pool = pool obj.save() else: # first entry - no POST data poolform = PoolForm(instance=pool) memberform = MemberForm(prefix='stock') if request.method == 'POST' and request.POST.get('action'): stock_list = request.POST.getlist('id') if request.POST.get('action') == 'Delete': if not len(stock_list): notify = Notify('Delete failed, select stock(s) to delete') else: notify = Notify('Delete stocks(s) {}?'.format(', '.join( StockPoolDates.objects.get(id=s).stock.name for s in stock_list))) notify.set_replies(request, ('Yes', 'No')) request.session['stock_delete_list'] = stock_list elif request.method == 'POST' and request.POST.get('reply'): stock_list = request.session.get('stock_delete_list') if not stock_list: raise AttributeError('session has no valid stock_delete_list') del request.session['stock_delete_list'] if request.POST.get('reply') == 'Yes': stocks = [StockPoolDates.objects.get(id=s).stock.name for s in stock_list] StockPoolDates.objects.filter(id__in=stock_list).delete() notify = Notify('Stock(s) {} deleted'.format(', '.join(stocks))) elif request.POST.get('reply') == 'No': notify = Notify('Delete cancelled') members = StockPoolDates.objects.filter(pool=pool).order_by('stock__name',) stocks_table = MembersTable(members, exclude=['pool',]) RequestConfig(request, paginate={'per_page': 100}).configure(stocks_table) return render(request, 'show_pool.html', { 'pool': pool, 'poolform': poolform, 'memberform': memberform, 'stocks_table': stocks_table, 'daterangeform': daterangeform, 'notify': notify, 'splits': splits, 'missing_prices': missing_prices, 'missing_channels': missing_channels, })
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, })