175 lines
5.0 KiB
Python
175 lines
5.0 KiB
Python
# Copyright (c) 2009 Andreas Balogh
|
|
# See LICENSE for details.
|
|
|
|
""" animated drawing of ticks
|
|
|
|
using blit method
|
|
"""
|
|
|
|
# system imports
|
|
|
|
import Tkinter as tk
|
|
import datetime
|
|
import os
|
|
import re
|
|
import logging
|
|
import sys
|
|
|
|
import matplotlib.pyplot as plt
|
|
from matplotlib.dates import date2num
|
|
import matplotlib.dates as mdates
|
|
import numpy as np
|
|
|
|
# local imports
|
|
|
|
# constants
|
|
|
|
# globals
|
|
|
|
LOG = logging.getLogger()
|
|
|
|
logging.basicConfig(level=logging.DEBUG,
|
|
format='%(asctime)s.%(msecs)03i %(levelname).4s %(process)d:%(thread)d %(message)s',
|
|
datefmt='%H:%M:%S')
|
|
|
|
MDF_REO = re.compile("(..):(..):(..)\.*(\d+)*")
|
|
|
|
def tdl(tick_date):
|
|
""" returns a list of tick tuples (cdt, last) for specified day """
|
|
fiid = "846900"
|
|
year = tick_date.strftime("%Y")
|
|
yyyymmdd = tick_date.strftime("%Y%m%d")
|
|
filename = "%s.csv" % (fiid)
|
|
filepath = os.path.join("d:\\rttrd-prd-var\\consors-mdf\\data", year, yyyymmdd, filename)
|
|
x = [ ]
|
|
y = [ ]
|
|
fh = open(filepath, "r")
|
|
try:
|
|
prev_last = ""
|
|
for line in fh:
|
|
flds = line.split(",")
|
|
# determine file version
|
|
if flds[2] == "LAST":
|
|
last = float(flds[3])
|
|
vol = float(flds[4])
|
|
else:
|
|
last = float(flds[4])
|
|
vol = 0.0
|
|
# skip ticks with same last price
|
|
if prev_last == last:
|
|
continue
|
|
else:
|
|
prev_last = last
|
|
# parse time
|
|
mobj = MDF_REO.match(flds[0])
|
|
if mobj is None:
|
|
raise ValueError("no match for [%s]" % (flds[0],))
|
|
(hh, mm, ss, ms) = mobj.groups()
|
|
if ms:
|
|
c_time = datetime.time(int(hh), int(mm), int(ss), int(ms) * 1000)
|
|
else:
|
|
c_time = datetime.time(int(hh), int(mm), int(ss))
|
|
cdt = datetime.datetime.combine(tick_date, c_time)
|
|
x.append(date2num(cdt))
|
|
y.append(last)
|
|
finally:
|
|
fh.close()
|
|
# throw away first line of file (close price from previous day)
|
|
del x[0]
|
|
del y[0]
|
|
return (x, y)
|
|
|
|
|
|
def main():
|
|
LOG.debug("Loading ticks...")
|
|
x, y = tdl(datetime.datetime(2009,6,3))
|
|
LOG.debug("Ticks loaded.")
|
|
|
|
fig = plt.figure()
|
|
ax1 = fig.add_subplot(311) # ticks
|
|
canvas = ax1.figure.canvas
|
|
# ax2 = fig.add_subplot(312) # gearing
|
|
# ax3 = fig.add_subplot(313) # cash
|
|
|
|
ax1.set_ylabel("ticks")
|
|
# ax2.set_ylabel("gearing")
|
|
# ax3.set_ylabel("cash")
|
|
|
|
xr = [x[0]] * 500
|
|
yr = [y[0]] * 500
|
|
|
|
line, = ax1.plot_date(xr, yr, '-', xdate = True)
|
|
major_fmt = mdates.DateFormatter('%H:%M:%S')
|
|
ax1.xaxis.set_major_formatter(major_fmt)
|
|
# ax1.axis('tight')
|
|
|
|
# format the coords message box
|
|
def price(x): return '%1.2f'%x
|
|
# ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
|
|
ax1.format_xdata = mdates.DateFormatter('%H:%M:%S')
|
|
ax1.format_ydata = price
|
|
ax1.grid(True)
|
|
|
|
# rotates and right aligns the x labels, and moves the bottom of the
|
|
# axes up to make room for them
|
|
fig.autofmt_xdate()
|
|
|
|
background = canvas.copy_from_bbox(ax1.bbox)
|
|
|
|
def animate():
|
|
w = 1000
|
|
bias = 10
|
|
|
|
ymin = min(y[0:100])
|
|
ymax = max(y[0:100])
|
|
|
|
low = ymin - bias
|
|
high = ymax + bias
|
|
trend = 0
|
|
|
|
for i in range(0, len(x)-w):
|
|
# restore the clean slate background
|
|
canvas.restore_region(background)
|
|
# prepare timeline window
|
|
xr = x[i:i+w]
|
|
yr = y[i:i+w]
|
|
# update line
|
|
line.set_xdata(xr)
|
|
line.set_ydata(yr)
|
|
# determine y axis
|
|
if yr[-1] > ymax:
|
|
ymax = yr[-1]
|
|
if ymax - 50 < min(yr):
|
|
ymin = ymax - 50
|
|
if yr[-1] < ymin:
|
|
ymin = yr[-1]
|
|
if ymin + 50 > max(yr):
|
|
ymax = ymin + 50
|
|
ax1.axis([xr[0], xr[-1], ymin, ymax])
|
|
# check low high and annotate
|
|
if i > 0 and i % 150 == 0:
|
|
ax1.annotate('low/high',
|
|
xy = (xr[-10], yr[-10]),
|
|
xytext = (xr[-5], yr[-10] + 10),
|
|
arrowprops = dict(facecolor = 'black',
|
|
frac = 0.2,
|
|
headwidth = 10,
|
|
linewidth = 0.1,
|
|
shrink = 0.05))
|
|
|
|
# just draw the animated artist
|
|
# FIXME: redraw all items in graph
|
|
ax1.draw_artist(line)
|
|
# just redraw the axes rectangle
|
|
canvas.blit(ax1.bbox)
|
|
|
|
|
|
|
|
root = fig.canvas.manager.window
|
|
root.after(100, animate)
|
|
plt.show()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|