Source

orgtool / orgtool / ext / finances / utils.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
# -*- coding: utf-8 -*-
#
#  Copyright (c) 2009—2010 Andrey Mikhailenko and contributors
#
#  This file is part of OrgTool.
#
#  OrgTool is free software under terms of the GNU Lesser
#  General Public License version 3 (LGPLv3) as published by the Free
#  Software Foundation. See the file README for copying conditions.
#
import datetime
from dateutil.relativedelta import relativedelta
from decimal import Decimal as D
import logging
import math
import urllib2
import re
import yaml

from tool import app

from orgtool.utils.timeseries import group_by_date


ROOT_MODULE = __name__.rpartition('.')[0]

logger = logging.getLogger(ROOT_MODULE)


class CalculationError(Exception):
    pass


def convert_currency(currency_from, currency_to, amount=1):
    """
    Converts currency using Google API. Does not cache rates. It is a good idea
    to store the rates in a local database and periodically update them using
    this function.
    """
    if currency_from == currency_to:
        return amount
    logger.debug('Converting {amount} {currency_from} to {currency_to} using '
                 'Google currency calculator'.format(**locals()))
    url_tmpl = ('http://google.com/ig/calculator?'
                'q={amount}{currency_from}%3D%3F{currency_to}')
    url = url_tmpl.format(**locals())
    response = urllib2.urlopen(url)
    # data string example:
    #   {lhs: "1 U.S. dollar",rhs: "0.767224183 Euros",error: "",icc: true}
    data_string = response.read().replace('\xa0', '') # strip separators
    data = yaml.load(data_string)
    if data['error']:
        raise CalculationError('Got error {error}'.format(**data))
    rate = re.search(r'^(\d+\.\d+)', data['rhs'])
    if not rate:
        raise CalculationError('Unexpected rate format: {rhs}'.format(**data))
    return D(rate.group(1).strip())


def get_default_currency():
    ext = app.get_feature('money')
    return unicode(ext.env['default_currency'])


# TODO: move this to Dark(?)
# Origin:
#     http://stackoverflow.com/questions/488670/calculate-exponential-moving-average-in-python
def calculate_ema(s, n=2, safe_period=True, ensure_series=True):
    """
    returns an n period exponential moving average for
    the time series s

    s is a list ordered from oldest (index 0) to most
    recent (index -1)
    n is an integer

    :param safe_period:
        automatically shrinks period if it's too large for given data set
    :param ensure_series:
        automatically prepends the series with a zero value if there's only one
        value in the series (this ensures a chart can be built).

    returns a numeric array of the exponential moving average
    """
    if not n:
        return

    s = list(s)
    if 1 == len(s):
        s = [0] + s
#        print 'single item:', s
#        return s

    ema = []

    if len(s) <= n:
        if safe_period:
            n = len(s) / 2
        else:
            raise ValueError('period {period} is too large for {cnt} data '
                             'items.'.format(period=n, cnt=len(s)))

    #get n sma first and calculate the next n period ema
    sma = sum(s[:n]) / n
    multiplier = 2 / D(1 + n)
    ema.append(sma)

    #EMA(current) = ( (Price(current) - EMA(prev) ) x Multiplier) + EMA(prev)
    ema.append(( (s[n] - sma) * multiplier) + sma)

    #now calculate the rest of the values
    j = 1
    for i in s[n+1:]:
       ema.append(ema[j] + (multiplier * (i - ema[j])))
       j += 1

    return ema

# TODO: extract this to a Tool template filter
def _get_rel_delta(dt, precision=2):
    now = datetime.datetime.utcnow()
    if not isinstance(dt, datetime.datetime):
        now = now.date()
    if dt < now:
        delta = relativedelta(now, dt)
    else:
        delta = relativedelta(dt, now)
    if delta.days or delta.months or delta.years:
        # TODO: i18n and i10n (ngettext, etc.)
        mapping = (
            (delta.years, u'years'),
            (delta.months, u'months'),
            (delta.days, u'days'),
        )
        parts = [(v,t) for v,t in mapping if v]
        used_parts = parts[:precision]
        is_past = bool(dt < now)
        return used_parts, is_past
    else:
        return [], False

def render_rel_delta(dt):
    parts, is_past = _get_rel_delta(dt)
    if parts:
        parts = [u'{0} {1}'.format(v,t) for v,t in parts]
        template = u'{0} ago' if is_past else u'in {0}'
        return template.format(' '.join(parts).strip())
    else:
        # _within_ a day; may be another calendar day
        return u'<strong>today</strong>'

def is_date_within_a_day(dt):
    parts, is_past = _get_rel_delta(dt)
    return not bool(parts)

def chart_url_for_payments(payments, width=300, height=100, scale='months',
                           max_intervals=6, currency=None, legend=True,
                           title=None):
    """ TODO:

    dark.aggregates: нужно получать разные агрегаты (сумма, кол-во) по группам
    и притом иметь возможность доступиться к исходным элементам через агрегат.

    Например, хочется поставить маркеры с текстом и датой для выдающихся
    платежей. Поскольку минимальное значение за период у нас зачастую получается
    суммированием отдельных значений (т.е. неск-ко платежей в течение месяца),
    мы не можем просто найти платеж с известной нам минимальной суммой: такого
    отдельного может просто не существовать. Поэтому маркером надо указывать
    вообще не на платеж, а на агрегированное значение. Возможно, при этом
    перечисляя описания соотв. платежей (как в ohloh). (Гуглодиаграммы
    поддерживают многострочные маркеры.)

    + надо корректно обрабатывать отсутствие данных на каких-то отрезках.
    Похоже, сейчас это не так просто. ГуглоAPI это умеет, но у нас тут всё
    завязано на нули, так что лучше пока не трогать.
    """
    assert max_intervals, 'unlimited depth is not (yet) supported'

    payments = payments.where_not(amount=None).order_by('date_time')  # NOT reversed
    until = datetime.datetime.utcnow()
    since = until - relativedelta(**{scale: max_intervals})
    payments = payments.where(date_time__gte=since)

    main_color, smooth_color = 'FFBF00', '8DB600', #'318CE7'   #, #'FE6F5E'# 'FAE7B5'
    grouped = group_by_date(payments, 'date_time', scale,
                            since=since, until=until)
    group_labels = []
    amounts = []
    scale_to_date_fmt = {
        'hours': '%H',
        'days': '%d',
        'months': '%b',
        'years': '%Y',
    }
    for date, group in grouped:
        fmt = scale_to_date_fmt.get(scale, '%d %b')
        label = date.strftime(fmt)
        group_labels.append(label)
        #group_labels.append(date.strftime('%b'))  # TODO: mind scale
        amounts.append(
            D(sum(p.get_amount_as(currency) if currency else p.amount
                             for p in group))
        )
    smoothing_period = len(amounts) / 3 or len(amounts) # 120->30, 14->6..10, 80->30
    smooth_data = calculate_ema(amounts, smoothing_period)
    if not smooth_data:
        return ''

    #_flat = lambda xs: ','.join(['{0:.2f}'.format(x) for x in xs])
    #smooth_series = _flat(smooth_data)
    min_amount = min(amounts)    #smooth_data if only_smooth else amounts)
    max_amount = max(amounts)    #smooth_data if only_smooth else amounts)
    safe_min_amount = min_amount - 1
    safe_max_amount = max_amount + 1
    if safe_max_amount < 0:
        safe_max_amount = 0
    if 0 < safe_min_amount:
        safe_min_amount = 0
#        if min_amount == max_amount:
#            min_amount = 0 if 0 < min_amount else -max_amount

    def _prep_boundary(x):
        value = math.ceil(abs(x))
        return -value if x < 0 else value
    min_y, max_y = [_prep_boundary(x) for x in (safe_min_amount,
                                                safe_max_amount)]

    span = (max_amount + abs(min_amount)) if 0 < max_amount else max_amount + min_amount
    if max_amount <= 0:
        zero_border = 1
    elif max_amount == span:
        zero_border = 0
    else:
        zero_border = max_amount * D('0.001')
    zero_border = D(zero_border).quantize(D('.1'))

    # positive balance (green)
    marker_positive = ''
    if 0 < max_amount:
        marker_positive = 'r,EEFFEE,0,{start},{end},{z_index}'.format(
            start = 1,
            end = zero_border,
            z_index = -2,
        )

    # negative balance (red)
    marker_negative = ''
    if min_amount < 0:
        marker_negative = 'r,FFEEEE,0,{start},{end},{z_index}'.format(
            start = zero_border,
            end = 0,
            z_index = -2,
        )

    # grid made out of markers. Simple grid would get hidden behind
    # positive/negative area merkers. It also didn't follow data ticks.
    marker_grid_v = 'V,cccccc,0,::1,0.5,-1'
    marker_grid_h = 'h,cccccc,0,0:2:.2,0.5,-1'

    markers = [
        marker_positive,
        marker_negative,
        marker_grid_v,
        marker_grid_h
    ]

    dynamic_markers = []
    """ TODO (no earlier than Dark gets smarter aggregates)
    def make_dynamic_marker(points, text):
        tmpl = 'y;s={style};d=bb,{text},{fg},{bg};ds={series};dp={points}'
        return tmpl.format(
            series = 0,   # axis A
            points = points,
            text = text,
            style = 'bubble_text_small', # icon_string_constant
            fg = 'ff0000',
            bg = 'ffffff',
        )
    # minimum value
    for aggregate in groups:
        if aggregate == min_amount:
            dm = make_dynamic_marker(
                points = ???,
                text = '\n'.join(p.summary for p in aggregate.items)
            )
            dynamic_markers.append(dm)
            print 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', dm
    # maximum value
    #...
    """

    chart = Chart(title, width, height, with_legend=legend)
    facts = Axis(
        range = (min_y, max_y),
        scale = (0, 100, min_y, max_y),
        align = 'y',
        color = main_color,
        style = '1',
        values = amounts,
        legend = 'Facts',
        labels = group_labels,
    )
    ema = Axis(
        range = (0, len(amounts)),
        scale = (0, 100, min_y, max_y),
        align = 'x',
        color = smooth_color,
        style = '2,3,2', # width=1, dash segment length=4, blank segment length=1
        values = smooth_data,
        legend = 'Average',
    )
    chart.axes.append(facts)
    chart.axes.append(ema)
    chart.markers = [m for m in markers if m]
    chart.dynamic_markers = dynamic_markers

    return chart.render()

    '''
    url = (
        'http://chart.apis.google.com/chart?'
        # plot title
        '&chtt={plot_title}'
        # axis labels
        '&chxl={axis_labels_a}'
        # axis label positions
        '&chxp={axis_label_pos_a}'
        # axis ranges
        '&chxr={axis_range_a}|{axis_range_b}'
        '&chxs=0,676767,11.5,0,lt,676767|1,676767,11.5,0,lt,676767'
        # visible axes
        '&chxt={axis_align_a},{axis_align_b}'
        '&chs={plot_width}x{plot_height}'
        '&cht=lxy'
        '&chco={axis_color_a},{axis_color_b}'
        # scale with custom range
        '&chds={axis_scale_a},{axis_scale_b}'
        '&chd=t:-1|{axis_values_a}|-1|{axis_values_b}'
        '&chdl={axis_legend_a}|{axis_legend_b}'
        '&chdlp=b'
#        '&chg={plot_grid_steps},{plot_grid_dash}'
        '&chls={axis_style_a}|{axis_style_b}'
        '&chma=5,5,5,25'
        # markers
        '&chm={markers}'
        '&chem={enhanced_markers}'
    ).format(
        plot_title = title,  # {since}—{until}'.format(**locals()),
        plot_width = width,
        plot_height = height,
        axis_range_a = join(0, min_y, max_y),
        axis_range_b = join(1, 0, len(amounts)),
        axis_align_a = 'y',
        axis_align_b = 'x',
        axis_color_a = main_color,
        axis_color_b = smooth_color,
        axis_style_a = '1',     # width=1
        axis_style_b = '2,3,2', # width=1, dash segment length=4, blank segment length=1
        # min scale, max scale, min value, max value
        axis_scale_a = join(0, 100, min_y, max_y),  # main data
        axis_scale_b = join(0, 100, min_y, max_y),  # smooth data
        # comma-separated series of values
        axis_values_a = join(*amounts),
        axis_values_b = join(*smooth_data),
        axis_legend_a = 'Facts',
        axis_legend_b = 'Average',
        # labels
        axis_labels_a = '1:|' + '|'.join(group_labels),
        axis_label_pos_a = '',  # ?
        # markers
        markers = '|'.join([m for m in markers if m]),
        enhanced_markers = '|'.join(dynamic_markers),
    )
#    return url
    '''


#--- TODO: extract code below to Dark(?)

def prep(val):
    #return '%.01f'%val if isinstance(val, float) else str(val)
    return str(val.quantize(D('.1'))) if isinstance(val, D) else str(val)

def join(*vals):
    return ','.join(prep(v) for v in vals)


class Chart(object):
    def __init__(self, title, width, height, with_legend=True):
        self.title = title
        self.width = width
        self.height = height
        self.axes = []
        self.markers = []
        self.dynamic_markers = []
        self.with_legend = with_legend

    def __str__(self):
        return self.render()

    def render(self):
        bits = '&'.join('='.join([k,v]) for k,v in self._url_bits() if v)
        return 'http://chart.apis.google.com/chart?' + bits

    def dump(self):
        for param, value in self._url_bits():
            print '{param}\t{value}'.format(**locals())

    def _collect_axis_labels(self):
        for i, axis in enumerate(self.axes, 1):
            if axis.labels:
                labels = '|'.join(str(x) for x in axis.labels if x)
                yield '{i}:|{labels}'.format(**locals())

    def _collect_axis_label_positions(self):
        for i, axis in enumerate(self.axes, 1):
            if axis.label_positions:
                labels = ','.join(str(x) for x in axis.labels if x)
                yield '{i},{labels}'.format(**locals())

    def _url_bits(self):
        # plot title
        if self.with_legend:
            yield 'chtt', self.title
            # axis labels
            yield 'chxl', '|'.join(self._collect_axis_labels())
            # axis label positions
            yield 'chxp', '|'.join(self._collect_axis_label_positions())
            yield 'chdl', '|'.join(a.legend for a in self.axes if a.legend)

        # axis ranges
        yield 'chxr', '|'.join('{0},{1},{2}'.format(i, *a.range)
                                    for i,a in enumerate(self.axes))
        yield 'chxs', '0,676767,11.5,0,lt,676767|1,676767,11.5,0,lt,676767'
        # visible axes
        yield 'chxt', ','.join(a.align for a in self.axes)
        yield 'chs', 'x'.join(str(x) for x in [self.width, self.height])
        yield 'cht', 'lxy'
        yield 'chco', ','.join(a.color for a in self.axes)
        # scale with custom range
        scales = (','.join(str(x) for x in a.scale) for a in self.axes)
        yield 'chds', ','.join(scales)
        values = (a.get_values() for a in self.axes)
        yield 'chd', 't:' + '|'.join(values)
        yield 'chdlp', 'b'
        yield 'chls', '|'.join(a.style for a in self.axes if a.style)
        yield 'chma', '5,5,5,25'
        # markers
        yield 'chm', '|'.join(m for m in self.markers)
        yield 'chem', '|'.join(m for m in self.dynamic_markers)


class Axis(object):
    def __init__(self, values, scale, range, labels=None,
                 label_positions=None, align='x', color='000000',
                 style='1', legend=None):
        self.values = values
        self.scale = scale
        self.range = range
        self.labels = labels
        self.label_positions = label_positions
        self.align = align
        self.color = color
        self.style = style
        self.legend = legend or None

    def get_values(self):
        return '-1|' + ','.join(prep(x) for x in self.values)