Пример #1
0
 def test_date2datestr(self):
     #default fmt:
     self.assertEqual(du.date2datestr(self.validdata[0]['date']), 
                 self.validdata[0]['str'])
     #with format specifier
     for data in self.validdata:
         self.assertEqual(du.date2datestr(data['date'], data['fmt']), 
                 data['str'])
     invalidformats = ('dmy', 'd/m/y', 'dd/mm/yy', 'mm-dd-yy', 'yy-mm-dd',)
     date = dt.date(2000, 1, 31)
     for fmt in invalidformats:
         self.assertRaises(ValueError, du.date2datestr, date, fmt)
Пример #2
0
def show_trade(request, trade_id):
    '''
    Show 2 states of a trade: day before entry and entry + exit (or open trade)
    '''
    trade = Trade.objects.get(id=trade_id)
#TODO: gcl = obsolete
    lookback = trade.method.rank.get_channel_lookback(trade=trade)
    if not lookback:
        lookback = Channel.YEAR

    if trade.rule_exit is not None:
        enddate = trade.date_exit
    else:
        enddate = datetime.date.today()
    trade.stock.date_range = (last_year(trade.date_entry), enddate)

    if trade.rule_exit is None:
        if request.method == 'POST':
            stoplossform = StoplossForm(request.POST)
            if stoplossform.is_valid():
                trade.date_exit = stoplossform.cleaned_data['startdate']
                angle = stoplossform.cleaned_data['angle']
                if angle is not None:
                    angle = int(angle)
                trade.price_exit = angle
                trade.save()
        stoplossform = StoplossForm(data={'angle': trade.price_exit, 
                'startdate': trade.date_exit })
        stoplossdate = next_weekday(trade.stock.get_latest_date())
    else:
        stoplossform = stoplossdate = stoploss = None

    entrychart = reverse('show_stock_chart_from_to_lookback', kwargs={
            'symbol': trade.stock.name, 
            'startdate_str': date2datestr(trade.date_entry - 
                datetime.timedelta(days=365)), 
            'enddate_str': date2datestr(trade.date_entry - 
                datetime.timedelta(days=1)),
            'lookback': lookback})
    exitchart = reverse('draw_trade_chart', kwargs={'trade_id': trade_id})

    if not trade.rule_exit:
        if trade.price_exit and trade.date_exit:
            # This is an open trade (portfolio position) with a custom stoploss
            stoploss = trade.stoploss()
        else:
            # This is an open trade (portfolio position) with default stoploss
            stoploss = trade.stock.price.channel.stoploss(lookback=lookback, 
                    date=stoplossdate, date_entry=trade.date_entry)

    # previous, next trade links:
    trades = trade.system.trade_set.order_by('date_entry')
    trade_id = int(trade_id)
    prev_id = prev_trade = next_trade = None
    for tr in trades:
        if prev_id == trade_id:
            next_trade = reverse('show_trade', kwargs={'trade_id': tr.id})
        if tr.id == trade_id and prev_id is not None:
            prev_trade = reverse('show_trade', kwargs={'trade_id': prev_id})
        prev_id = tr.id

    return render(request, 'show_trade.html',{
            'trade': trade,
            'entrychart': entrychart,
            'exitchart': exitchart,
            'entry_data': trade.stock.data_summary(
                trade.stock.price.close.get_date(
                trade.date_entry, -1), lookback),
            'exit_data': trade.stock.data_summary(enddate, lookback),
            'prev_trade': prev_trade,
            'next_trade': next_trade,
            'stoplossdate': stoplossdate,
            'stoploss': stoploss,
            'stoplossform': stoplossform})
Пример #3
0
def show_stock(request, stock_id=None, symbol=None):
    '''
    Show stock chart and metrics. 
    '''
#CONSIDER: add indicators that can dynamically be selected/changed
    if stock_id:
        stock = Stock.objects.get(id=stock_id)
    elif symbol:
        stock = Stock.objects.get(name=symbol.upper())
    else:
        raise SystemExit('Fatal Error: no stock_id or symbol specified.')

    missing_prices = stock.missing_prices()
    if not missing_prices:
        missing_channels = stock.missing_channels()
        splits = stock.check_splits()
    else:
        missing_channels = []
        splits = []

    #set default date range and lookback period:
    lookback = request.session.get('channel_lookback_period', Channel.YEAR)
    enddate = datetime.date.today()
    startdate = enddate - datetime.timedelta(days=365)

    if request.method == 'POST':
        reload_ = False

        if request.POST.get('todo') == 'Download missing prices':
            fromdate = min(missing_prices)
            todate = max(missing_prices)
            stock.download_history(fromdate, todate)
            reload_ = True

        if request.POST.get('todo') == 'Calculate missing channels':
            fromdate = min(missing_channels)
            todate = max(missing_channels)
            Channel.calculate(stock, fromdate, todate)
            reload_ = True

        if request.POST.get('todo') == 'Correct prices for split':
            stock.correct_splits()
            reload_ = True

        if reload_:
            if symbol:
                return redirect('show_symbol', symbol=symbol)
            else:
                return redirect('show_stock', stock_id=stock_id)

        if request.POST.get('todo') == 'Save settings':
            stockchartform = StockChartForm(request.POST)
            if stockchartform.is_valid():
                sd = stockchartform.cleaned_data['startdate']
                ed = stockchartform.cleaned_data['enddate']
                if sd:
                    startdate = sd
                if ed:
                    enddate = ed
                lookback = int(stockchartform.cleaned_data['lookback_period'])
                request.session['channel_lookback_period'] = lookback
        else:
            stockchartform = StockChartForm(initial={'startdate': startdate,
                    'enddate': enddate, 'lookback_period': lookback})
    else:
        stockchartform = StockChartForm(initial={'startdate': startdate,
                'enddate': enddate, 'lookback_period': lookback})

    stockchart = reverse('show_stock_chart_from_to', kwargs={
            'symbol': stock.name,
            'startdate_str': date2datestr(startdate),
            'enddate_str': date2datestr(enddate),})

    return render(request, 'show_stock.html',
                {'stock': stock,
                 'data': stock.data_summary(enddate, lookback),
                 'missing_prices': missing_prices,
                 'missing_channels': missing_channels,
                 'splits': splits,
                 'stockchart': stockchart,
                 'stockchartform': stockchartform})