← All archived writing

Quickly run up microservices for your trading apps

Originally published on quanttech.co. View saved original ↗

In todays world of microservices, Flask is a great compact framework in Python for quickly creating web services. For simple services, it's faster to work with then Django (which incidentally is great for more complex services/sites).

For instance, you can build a self-contained service that serves up random price data over JSON, in 15 lines of code!

You start by installing Flask:

pip install Flask

Then create a simple wrapper around your library. In this instance our library is one we have seen before which generates prices using a geometric Brownian motion process.

from flask import app, Flask, jsonify, request
import bm


app = Flask(__name__)


@app.route('/gbm')
def gbm():
    args = request.args

    periods = int(args.get('periods'))
    start_price = float(args.get('startPrice'))
    mu = float(args.get('mu'))
    sigma = float(args.get('sigma'))
    delta = float(args.get('delta'))

    prices = bm.generate_gbm_prices(periods, start_price, mu, sigma, delta)
    return jsonify(result=prices.tolist())


if __name__ == "__main__":
    app.run()

We the run our application:

$ python price_service.py
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [23/Jun/2015 21:33:06] "GET /gbm?periods=100&startPrice=70.0&mu=0.05&sigma=0.30&delta=1.0 HTTP/1.1" 200 -
...

And verify we're getting data back!

service response

You can use the following unit test to validate the service:

import json
import unittest

from services import price_service


class ServicesTest(unittest.TestCase):
    def setUp(self):
        self.app = price_service.app.test_client()

    def test_gbm(self):
        data = {
            'periods': 100,
            'startPrice': 70.0,
            'mu': 0.05,
            'sigma': 0.30,
            'delta': 1.0
        }

        response = self.app.get('/gbm', query_string=data)
        self.assertEqual(200, response.status_code)
        data = json.loads(response.get_data().decode('utf-8'))
        self.assertEqual(100, len(data['result']))

This gives you a nice easy way to scale up your dumb (non-persistent) services to reside onto separate hosts or containers.

Full code is available here.

Cite this post

Conor Svensson (23 June 2015). Quickly run up microservices for your trading apps. https://conorsvensson.com/archive/quanttech/quickly-run-up-microservices-for-your-trading-apps/

BibTeX
@misc{svensson2015-quickly-run-up-microservices-for-your-trading-apps,
  author = {Conor Svensson},
  title = {{Quickly run up microservices for your trading apps}},
  year = {2015},
  month = jun,
  url = {https://conorsvensson.com/archive/quanttech/quickly-run-up-microservices-for-your-trading-apps/}
}