Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@yhilpisch
Last active December 18, 2018 14:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save yhilpisch/7dc47060eb51954d7aa2a576e6380d5f to your computer and use it in GitHub Desktop.
Save yhilpisch/7dc47060eb51954d7aa2a576e6380d5f to your computer and use it in GitHub Desktop.

Executive Program in Algorithmic Trading (QuantInsti)

Python Sessions by Dr. Yves J. Hilpisch | The Python Quants GmbH

Online, 25. & 26. August 2018

Short Link

http://bit.ly/epat_aug_2018

Resources

Slides & Materials

You find the introduction slides under http://hilpisch.com/epat.pdf

You find the materials about OOP under http://hilpisch.com/py4fi_oop_epat.html

Python

If you have either Miniconda or Anaconda already installed, there is no need to install anything new.

The code that follows uses Python 3.6. For example, download and install Miniconda 3.6 from https://conda.io/miniconda.html if you do not have conda already installed.

In any case, for Linux/Mac you should execute the following lines on the shell to create a new environment with the needed packages:

conda create -n epat python=3.6
source activate epat
conda install numpy pandas matplotlib statsmodels
pip install plotly==2.4.0 cufflinks
conda install ipython jupyter
jupyter notebook

On Windows, execute the following lines on the command prompt:

conda create -n epat python=3.6
activate epat
conda install numpy pandas matplotlib statsmodels
pip install plotly==2.4.0 cufflinks
pip install win-unicode-console
set PYTHONIOENCODING=UTF-8
conda install ipython jupyter
jupyter notebook

Read more about the management of environments under https://conda.io/docs/using/envs.html

Docker

To install Docker see https://docs.docker.com/install/.

To run a Ubuntu-based Docker container, execute on the shell the following:

docker run -ti -p 9000:9000 -h epat -v /Users/yves/Temp/:/root/tmp ubuntu:latest /bin/bash

Make sure to adjust the folder to be mounted accordingly.

ZeroMQ

The major resource for the ZeroMQ distributed messaging package based on sockets is http://zeromq.org/

Cloud

Use this link to get a 10 USD bonus on DigitalOcean when signing up for a new account.

Books & Resources

An overview of the Python Data Model is found under: Python Data Model

Good book about everything important in Python data analysis: Python Data Science Handbook, O'Reilly

Good book covering object-oriented programming in Python: Fluent Python, O'Reilly

Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
#
# SMA-based Online Trading Algorithm
# ("Algorithmic Trading Simulator")
#
import zmq
import pandas as pd
import datetime as dt
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect('tcp://127.0.0.1:5555')
socket.setsockopt_string(zmq.SUBSCRIBE, '')
raw = pd.DataFrame()
SMA1 = 5
SMA2 = 10
min_length = SMA2 + 1
position = 0
ticks = 0
while True:
ticks += 1
msg = socket.recv_string()
t = dt.datetime.now()
print('{} | '.format(str(t)) + msg)
symbol, price = msg.split()
price = float(price)
raw = raw.append(pd.DataFrame({symbol: price}, index=[t,]))
data = raw.resample('3s', label='right').last().ffill()
if len(data) > min_length:
min_length += 1
data['SMA1'] = data[symbol].rolling(SMA1).mean()
data['SMA2'] = data[symbol].rolling(SMA2).mean()
if position in [0, -1]:
if data['SMA1'].iloc[-2] > data['SMA2'].iloc[-2]:
print('\n*** GOING LONG ***\n')
position = 1
# place your trading logic/code
print(data.tail(), '\n')
elif position in [0, 1]:
if data['SMA1'].iloc[-2] < data['SMA2'].iloc[-2]:
print('\n*** GOING SHORT ***\n')
position = -1
# place your trading logic/code
print(data.tail(), '\n')
#
# Simple Tick Data Client
# ("Algorithmic Trading Simulator")
#
import zmq
import datetime as dt
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect('tcp://127.0.0.1:5555')
socket.setsockopt_string(zmq.SUBSCRIBE, '')
while True:
msg = socket.recv_string()
t = dt.datetime.now()
print('{} | '.format(str(t)) + msg)
#
# Simple Tick Data Collector
# ("Algorithmic Trading Simulator")
#
import zmq
import pandas as pd
import datetime as dt
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect('tcp://127.0.0.1:5555')
socket.setsockopt_string(zmq.SUBSCRIBE, '')
raw = pd.DataFrame()
ticks = 0
while True:
ticks += 1
msg = socket.recv_string()
t = dt.datetime.now()
print('{} | '.format(str(t)) + msg)
symbol, price = msg.split()
price = float(price)
raw = raw.append(pd.DataFrame({symbol: price}, index=[t,]))
#if ticks % 100 == 0:
# h5 = pd.HDFStore('tick_data.h5', 'a')
# h5[symbol] = raw
# h5.close()
#
# Simple Tick Data Server
# ("Financial Market Simulator")
#
import zmq
import time
import random
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind('tcp://127.0.0.1:5555')
AAPL = 100.
while True:
AAPL += random.gauss(0, 1) * 0.5
msg = 'AAPL {:.2f}'.format(AAPL)
socket.send_string(msg)
print(msg)
time.sleep(random.random() * 2)
#
# Simple Tick Data Client
#
import zmq
import datetime
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect('tcp://127.0.0.1:5555')
socket.setsockopt_string(zmq.SUBSCRIBE, '')
while True:
msg = socket.recv_string()
t = datetime.datetime.now()
print(str(t) + ' | ' + msg)
#
# Simple Tick Data Collector
#
import zmq
import datetime
import pandas as pd
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect('tcp://127.0.0.1:5555')
socket.setsockopt_string(zmq.SUBSCRIBE, '')
raw = pd.DataFrame()
while True:
msg = socket.recv_string()
t = datetime.datetime.now()
print(str(t) + ' | ' + msg)
symbol, price = msg.split()
raw = raw.append(pd.DataFrame({'SYM': symbol, 'PRICE': float(price)}, index=[t]))
data = raw.resample('5s', label='right').last()
if len(data) % 4 == 0:
print(50 * '=')
print(data.tail())
print(50 * '=')
# simple way of storing data, needs to be adjusted for your purposes
if len(data) % 20 == 0:
# h5 = pd.HDFStore('database.h5', 'a')
# h5['data'] = data
# h5['raw'] = raw
# h5.close()
pass
#
# Simple Tick Data Plotter with ZeroMQ & http://plot.ly
#
import zmq
import datetime
import plotly.plotly as ply
from plotly.graph_objs import *
import configparser
# credentials
c = configparser.ConfigParser()
c.read('../pyalgo.cfg')
stream_ids = c['plotly']['api_tokens'].split(',')
# socket
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect('tcp://127.0.0.1:5555')
socket.setsockopt_string(zmq.SUBSCRIBE, '')
# plotting
s = Stream(maxpoints=100, token=stream_ids[0])
tr = Scatter(x=[], y=[], name='tick data', mode='lines+markers', stream=s)
d = Data([tr])
l = Layout(title='EPAT Tick Data Example')
f = Figure(data=d, layout=l)
ply.plot(f, filename='epat_example', auto_open=True)
st = ply.Stream(stream_ids[0])
st.open()
while True:
msg = socket.recv_string()
t = datetime.datetime.now()
print(str(t) + ' | ' + msg)
sym, value = msg.split()
st.write({'x': t, 'y': float(value)})
#
# Simple Tick Data Server
#
import zmq
import time
import random
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind('tcp://127.0.0.1:5555')
AAPL = 100.
while True:
AAPL += random.gauss(0, 1) * 0.5
msg = 'AAPL %.3f' % AAPL
socket.send_string(msg)
print(msg)
time.sleep(random.random() * 2)
gist -u 7dc47060eb51954d7aa2a576e6380d5f *
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment