Neil Robinson

welcome to my personal blog

Grab PE Ratio from Google Finance in python

Purpose:

Essentially what this code grabs the PE ratio and calculates the V* (Benjamin Graham formula)

Instructions

the page variable needs to be modified to the stock that you want. The default setting is currently set at RY (Royal Bank of Canada).

Code

#!/usr/bin/python
#grab_pe_ratio.py
#Use freely in any manner you like; I assume no liable for any damages that you may cause. :)
#Written by Neil Robinson

from lxml import html
import requests

#page = requests.get('http://www.google.com/finance?q=TSE%3AREI.UN')
page = requests.get('http://www.google.com/finance?q=RY')
tree = html.fromstring(page.content)

pe_ratio_d = tree.xpath('//td[@class="key"]/text()')
pe_ratio = tree.xpath('//td[@class="val"]/text()')

print 'PE Ratio: ', pe_ratio_d[5]
print 'PE Ratio: ', pe_ratio[5]

print 'V*: ', float(pe_ratio[5])*((8.5+2*.1))

Output on August 19, 2016:

PE Ratio: P/E

PE Ratio: 12.19

V*: 106.053