-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVolatility
executable file
·49 lines (37 loc) · 1.42 KB
/
Volatility
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/python3
"""Scrapes finviz.com to get the weekly and monthly volatility percentage."""
import argparse
from bs4 import BeautifulSoup
import requests
def GetHTML(ticker):
url = 'https://finviz.com/quote.ashx?t={}&ty=c&p=d&b=1'.format(ticker)
user_agent = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'
resp = requests.get(url, headers={'User-Agent': user_agent})
return resp.text
def GetVolatility(html):
soup = BeautifulSoup(html, 'html.parser')
elems = soup.select('table.snapshot-table2 td')
indices = {}
for i, elem in enumerate(elems):
indices[elem.text.lower().strip()] = i + 1
vol_week, vol_month = elems[indices['volatility']].text.split()
return {'WeeklyVolatility': vol_week,
'MonthlyVolatility': vol_month,
'ATR': elems[indices['atr']].text,
'Price': elems[indices['price']].text}
def main(args):
for ticker in args.tickers:
html = GetHTML(ticker)
vals = GetVolatility(html)
vals['Ticker'] = ticker
vals['ATRPercent'] = (float(vals['ATR'])/float(vals['Price'])) * 100
print(('{Ticker}\t'
'VW:{WeeklyVolatility} '
'VM:{MonthlyVolatility} '
'ATR:{ATR} '
'ATR%:{ATRPercent:.1f}').format(**vals))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('tickers', nargs='+')
args = parser.parse_args()
main(args)