Python for Finance: Analyze Big Financial Data

(Elle) #1

We will now dive into the example application called Tradechat for a traders’ chat room,


which basically relies on the example used in the tutorial of the Flask documentation but


includes a couple of changes and adds some further functionality.


[ 58 ]

The basic idea is to build a web-based application for which traders can register that


provides one central chat room to exchange ideas and talk markets. The main screen shall


allow a user who is logged in to type in text that is, after pushing a button, added to the


timeline, indicating who added the comment and when this happened. The main screen


also shows all the historical entries in descending order (from newest to oldest).


Data Modeling


We start by generating the needed directories. tradechat shall be the main directory. In


addition, at a minimum, we need the two subdirectories static and templates (by Flask


convention):


$   mkdir   tradechat
$ mkdir tradechat/static
$ mkdir tradechat/templates

To store data — both for registered users and for comments made in the chat room — we


use SQLite3 (cf. http://www.sqlite.org and http://docs.python.org/2/library/sqlite3.html) as


a database. Two different tables are needed that can be generated by the SQL schema


presented in Example 14-1, the details of which we do not discuss here. You should store


this under the filename tables.sql in the main directory of the application, tradechat.


Example 14-1. SQL schema to generate tables in SQLite3


drop table if exists comments;
create table comments (
id integer primary key autoincrement,
comment text not null,
user text not null,
time text not null
);


drop table if exists users;
create table users (
id integer primary key autoincrement,
name text not null,
password text not null
);


The Python Code


The SQL schema is a main input for the Python/Flask application to follow. We will go


through the single elements step by step to finally arrive at the complete Python script to


be stored under tradechat.py in the main directory, tradechat.


Imports and database preliminaries


At the beginning we need to import a couple of libraries and also some main functions


from Flask. We import the functions directly to shorten the code throughout and increase


readability somewhat:


#   Tradechat
#
# A simple example for a web-based chat room
# based on Flask and SQLite3.
#

import os
Free download pdf