Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Code from Plotcon, 04. May 2017, Oakland

Streaming Financial Data & Plots with Ploty

This Gist hosts the code from my talk and brief coding session at Plotcon.

  • tick data server with ZeroMQ
  • tick data client with ZeroMQ
  • tick data plotting with plotly
  • Flask app embedding the streaming plot

Slides under http://hilpisch.com/plotcon.pdf

#
# Tick Data Server
#
import zmq
import time
import random
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind('tcp://0.0.0.0:5555')
AMZN = 100.
while True:
AMZN += random.gauss(0, 1) * 0.5
msg = 'AMZN %s' % AMZN
socket.send_string(msg)
print(msg)
time.sleep(random.random() * 2)
#
# Tick Data Client
#
import zmq
import datetime
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect('tcp://0.0.0.0:5555')
socket.setsockopt_string(zmq.SUBSCRIBE, '')
while True:
msg = socket.recv_string()
t = datetime.datetime.now()
print(str(t) + ' | ' + msg)
#
# Tick Data Plot
#
import zmq
import datetime
import plotly.plotly as ply
from plotly.graph_objs import *
import plotly.tools as pls
stream_ids = pls.get_credentials_file()['stream_ids']
# socket
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect('tcp://0.0.0.0:5555')
socket.setsockopt_string(zmq.SUBSCRIBE, '')
# plotly
s = Stream(maxpoints=100, token=stream_ids[0])
t = Scatter(x=[], y=[], name='tick data', mode='lines+markers', stream=s)
d = Data([t])
l = Layout(title='Tick Data Stream')
f = Figure(data=d, layout=l)
ply.plot(f, filename='plotcon', auto_open=True)
st = ply.Stream(stream_ids[0])
st.open()
while True:
msg = socket.recv_string()
t = datetime.datetime.now()
sym, value = msg.split()
print(str(t) + ' | ' + msg)
st.write({'x': t, 'y': float(value)})
#
# Flask Hello World
#
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return '<iframe src="https://plot.ly/~yves/1041/tick-data-stream/" width="750px" height="550px"></iframe>'
if __name__ == '__main__':
app.run(port=9999, debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment