Professional Documents
Culture Documents
Python (Part 2)
Edward Khon
ekhon@virtu.com
+
Our Best Friends
n Google
n https://www.google.com
n FS Dev
n Ops Scripts
>>> mylist
['p', 'i', 'n', 'e', 'a', 'p', 'p', 'l', 'e']
>>> mylist[2:]
['n', 'e', 'a', 'p', 'p', 'l', 'e']
>>> mylist[:5]
['p', 'i', 'n', 'e', 'a']
>>> mylist[-2:]
['l', 'e']
>>> mylist[:-2]
['p', 'i', 'n', 'e', 'a', 'p', 'p']
>>> mylist[3:-2]
['e', 'a', 'p', 'p']
>>> mylist[::2]
['p', 'n', 'a', 'p', 'e']
>>> mylist[::-1]
['e', 'l', 'p', 'p', 'a', 'e', 'n', 'i', 'p']
+
List Comprehensions
... squares.append(x**2)
...
>>> squares
n File reading
n Loading a CSV configuration file
n Analyzing a log file
n File writing
n Producing configuration files
n Writing to a log file
n Transforming the contents of an existing file
n f = open(filename, mode)
n E.g. open(/prod/file.txt, r)
n Modes: r for reading, w for writing, r+ for both, a for
appending
n w erases the contents of the file if one exists
+
Operating on files
n f.read()
n Returns the entire contents of the file as a String
n f.readline()
n Reads the next line of the file
>>> import re
>>> re.findall("\d+", "S0m3 c0mb1n4t10n 0f 13773rs and numb3rs")
['0', '3', '0', '1', '4', '10', '0', '13773', '3']
>>> re.match(".*(DE\d{10})", "The German ISIN is DE0124315323").group(1)
'DE0124315323'
>>> symbols = "AAPL, GOOG, TSE:1570, OSE:NK2M6, SGX:INN6, CLZ5"
>>> re.findall("[A-Z0-9]+[FGHJKMNQUVXZ]\d", symbols)
['NK2M6', 'INN6', 'CLZ5']
>>> re.findall("[A-Z0-9]+:?[A-Z0-9]+[FGHJKMNQUVXZ]\d", symbols)
['OSE:NK2M6', 'SGX:INN6', 'CLZ5']
+
Classes
n Use the self keyword for accessing fields and methods from
within an object
+
Classes Example
class Strategy:
def __init__(self, name, mark_price, multiplier=1):
self.name = name
self.multiplier = multiplier
self.mark_price = mark_price
self.pnl = 0
self.volume = 0
self.position = 0
def print_status(self):
print "%s PNL: %s Volume: %s Position: %s" % (self.name, self.pnl, self.volume, self.position)
strat1.print_status()
strat2.print_status()
+
Built-ins
>>> len("hello")
n len() 5
>>> len(["i", "t", "s", "m", "e"])
n enumerate() 5
>>> list(enumerate(["a", "b", "c"]))
n type() [(0, 'a'), (1, 'b'), (2, 'c')]
n Returns what kind of object a >>> type("Python")
variable is <type 'str'>
>>> type([1,2,3])
n isinstance() <type 'list'>
n Say you want to open a file and read it, but even if it doesnt
its okay for your project
try:
f = open("myfile.txt", "r")
# Do something with the file
except IOError as e:
print "I/O error %s: %s" % (e.errno, e.strerror)
n CamelCase or under_scores
n Up to you, but be consistent
n Prodscripts plug into Java classes which are in CamelCase, so that
choice might be obvious