Initial checkin
--HG-- branch : sandbox
This commit is contained in:
163
mpl/mpl-draw.py
Normal file
163
mpl/mpl-draw.py
Normal file
@@ -0,0 +1,163 @@
|
||||
# Copyright (c) 2008 Andreas Balogh
|
||||
# See LICENSE for details.
|
||||
|
||||
""" animated drawing of ticks
|
||||
|
||||
using draw 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
|
||||
# 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()
|
||||
|
||||
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):
|
||||
# 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))
|
||||
|
||||
fig.canvas.draw()
|
||||
|
||||
root = fig.canvas.manager.window
|
||||
root.after(100, animate)
|
||||
plt.show()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user