Python for Finance: Analyze Big Financial Data

(Elle) #1

Finally, we should close the connection to the FTP server:


In  [ 12 ]: ftp.close()

In the local directory there are now two files, the one that was generated locally and the


one generated by retrieving the file from the server:


In  [ 13 ]: !ls -n  ./data
<<<<<<< HEAD
Out[13]: insgesamt 156
-rw––- 1 1000 1000 77824 Sep 15 08:14 array_ftp.npy
-rw––- 1 1000 1000 80080 Sep 15 08:14 array.npy
=======
Out[13]: insgesamt 156
-rw––- 1 1000 1000 77824 Sep 29 17:05 array_ftp.npy
-rw––- 1 1000 1000 80080 Sep 29 17:05 array.npy
>>>>>>> 798603793467fffcd06a9df88edf091e339dec37
In [ 14 ]: !rm -f ./data/arr*
# cleanup directory

All that has happened so far was done without encryption (i.e., was fully insecure). Both


login information and data were transferred in readable form. However, for most


applications such operations should be encrypted so others are not able to read the data


and/or steal the login information and do even worse things.


ftplib can connect to FTP servers securely via the function FTP_TLS. Once such a secure


connection is established, all other operations remain the same:


In  [ 15 ]: ftps    =   ftplib.FTP_TLS(‘quant-platform.com’)
In [ 16 ]: ftps.login(user=‘python’, passwd=‘python’)
Out[16]: ‘230 Login successful.’
In [ 17 ]: ftps.prot_p()
Out[17]: ‘200 PROT now Private.’
In [ 18 ]: ftps.retrlines(‘LIST’)
Out[18]: ‘226 Directory send OK.’
In [ 19 ]: ftps.close()

httplib


Another important protocol, if not the most important one on the Web, is the HyperText


Transfer Protocol (HTTP).


[ 51 ]

This protocol is used whenever a (HTML-based) web page is


displayed in the browser. The Python library to work with HTTP is called httplib:


In  [ 20 ]: import httplib

As with FTP, we first need a connection to the HTTP server:


In  [ 21 ]: http    =   httplib.HTTPConnection(‘hilpisch.com’)

Once the connection is established, we can send requests, for example asking for the


index.htm page (file):


In  [ 22 ]: http.request(‘GET’, ‘/index.htm’)

To test whether this was successful, use the getresponse method:


In  [ 23 ]: resp    =   http.getresponse()

The returned object provides status information. Fortunately, our request was successful:


In  [ 24 ]: resp.status,    resp.reason
Out[24]: (200, ‘OK’)

Equipped with the response object, we can now read the content as follows:

Free download pdf