-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathstocktwits.py
63 lines (51 loc) · 2.37 KB
/
stocktwits.py
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/python3
from scrape import scrape_page
BASE_URL = "http://stocktwits.com/symbol/"
BULLISH_SENTIMENT_XPATH = '//*[@id="sentiment-chart"]/div/ul/li[1]/span/text()'
BEARISH_SENTIMENT_XPATH = '//*[@id="sentiment-chart"]/div/ul/li[2]/span/text()'
def get_bullish_sentiment(ticker_symbol, page=None):
"""
Gets the bullish sentiment of the target ticker symbol
:param ticker_symbol: The ticker symbol of the interested stock (e.g., "AAPL", "GOOG", "MSFT")
:param page: html tree structure based on the html markup of the scraped website
:return: a string of the percentage of bullish sentiment as listed on a stock's StockTwit's page
"""
if page is None:
page = scrape_page(BASE_URL + ticker_symbol)
sentiment = page.xpath(BULLISH_SENTIMENT_XPATH)
if not sentiment:
return None
else:
return sentiment[0].replace("\n", "") + " Bullish"
def get_bearish_sentiment(ticker_symbol, page=None):
"""
Gets the bearish sentiment of the target ticker symbol
:param ticker_symbol: The ticker symbol of the interested stock (e.g., "AAPL", "GOOG", "MSFT")
:param page: html tree structure based on the html markup of the scraped website
:return: a string of the percentage of bearish sentiment as listed on a stock's StockTwits page
"""
if page is None:
page = scrape_page(BASE_URL + ticker_symbol)
sentiment = page.xpath(BEARISH_SENTIMENT_XPATH)
if not sentiment:
return None
else:
return sentiment[0].replace("\n", "") + " Bearish"
def get_sentiment(ticker_symbol, page=None):
"""
Gets both the bullish and bearish sentiment of the target ticker symbol
:param ticker_symbol: The ticker symbol of the interested stock (e.g., "AAPL", "GOOG", "MSFT")
:param page: html tree structure based on the html markup of the scraped website
:return: a tuple of strings containing both the bullish and bearish sentiment as listed on a stock's
StockTwits page
"""
if page is None:
page = scrape_page(BASE_URL + ticker_symbol)
bullish_sentiment = get_bullish_sentiment(ticker_symbol, page)
if bullish_sentiment:
return bullish_sentiment, get_bearish_sentiment(ticker_symbol, page)
else:
return None
if __name__ == "__main__":
# Test cases
print(get_sentiment("AAPL"))