Skip to content

Instantly share code, notes, and snippets.

@yhilpisch
Last active September 19, 2018 18:51
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yhilpisch/144842de32228f2888614fb45f1952d9 to your computer and use it in GitHub Desktop.
Save yhilpisch/144842de32228f2888614fb45f1952d9 to your computer and use it in GitHub Desktop.
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