Created
February 23, 2021 14:31
-
-
Save aaroncouch/13098d450ab5b780f6034d338d5b50d7 to your computer and use it in GitHub Desktop.
Simple method to get Yahoo's Analyst PTs and Recommendation Ratings.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import re | |
| import json | |
| import requests | |
| from bs4 import BeautifulSoup | |
| class YahooAnalysis: | |
| def __init__(self, ticker): | |
| self.financial_data = {} | |
| try: | |
| response = requests.get( | |
| url=f"https://finance.yahoo.com/quote/{ticker}/analysis?p={ticker}" | |
| ) | |
| response.raise_for_status() | |
| except requests.exceptions.RequestException as error: | |
| # It would be more appropriate to re-raise the error here, but in context this works | |
| # better for me. | |
| print(error) | |
| response = None | |
| if response is not None: | |
| soup = BeautifulSoup(response.text, "html.parser") | |
| scripts = soup.findAll("script") | |
| data = json.loads(re.search("root.App.main\s+=\s+(\{.*\})", str(scripts)).group(1)) | |
| self.financial_data = data["context"]["dispatcher"]["stores"]["QuoteSummaryStore"][ | |
| "financialData" | |
| ] | |
| def get_analyst_data(self): | |
| data = { | |
| "analyst_count": None, | |
| "analyst_rating": None, | |
| "analyst_rating_key": None, | |
| } | |
| if self.financial_data: | |
| if self.financial_data["numberOfAnalystOpinions"]: | |
| data["analyst_count"] = self.financial_data["numberOfAnalystOpinions"]["raw"] | |
| if self.financial_data["recommendationMean"]: | |
| data["analyst_rating"] = self.financial_data["recommendationMean"]["raw"] | |
| if self.financial_data["recommendationKey"]: | |
| data["analyst_rating_key"] = self.financial_data["recommendationKey"] | |
| return data | |
| def get_target_price_data(self): | |
| data = { | |
| "low_target": None, | |
| "median_target": None, | |
| "mean_target": None, | |
| "high_target": None, | |
| } | |
| if self.financial_data: | |
| if self.financial_data["targetLowPrice"]: | |
| data["low_target"] = self.financial_data["targetLowPrice"]["raw"] | |
| if self.financial_data["targetMedianPrice"]: | |
| data["median_target"] = self.financial_data["targetMedianPrice"]["raw"] | |
| if self.financial_data["targetMeanPrice"]: | |
| data["mean_target"] = self.financial_data["targetMeanPrice"]["raw"] | |
| if self.financial_data["targetHighPrice"]: | |
| data["high_target"] = self.financial_data["targetHighPrice"]["raw"] | |
| return data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment