In the ever-evolving landscape of financial information, Yahoo! Finance has consistently been at the forefront, providing users with comprehensive data to make informed investment decisions. One of the key features enhancing the user experience is the integration of the Benzinga Analyst Ratings API, which enables Yahoo to present up-to-date and insightful analyst ratings on their website. In this blog, we will delve into the mechanics of how Yahoo utilizes the Benzinga Analyst Ratings API, offering users a seamless and dynamic experience.
Understanding the Benzinga Analyst Ratings API
Benzinga offers an Analyst Ratings API that provides real-time information on analyst sentiment and recommendations for various financial instruments. Yahoo has strategically incorporated this API to enhance its financial content, specifically focusing on the analyst ratings section.
{
"ratings": [
{
"action_company": "Maintains",
"action_pt": "Raises",
"adjusted_pt_current": "80.00",
"adjusted_pt_prior": "60.00",
"analyst": "Truist Securities",
"analyst_name": "Joel Fishbein",
"currency": "USD",
"date": "2024-02-07",
"exchange": "NASDAQ",
"id": "65c3f523dc73050001d8c3b3",
"importance": 0,
"name": "Fortinet",
"notes": "",
"pt_current": "80",
"pt_prior": "60.0000",
"rating_current": "Buy",
"rating_prior": "Buy",
"ticker": "FTNT",
"time": "16:24:51",
"updated": 1707341137,
"url": "https://www.benzinga.com/quote/FTNT/analyst-ratings",
"url_calendar": "https://www.benzinga.com/quote/FTNT/analyst-ratings",
"url_news": "https://www.benzinga.com/stock-articles/FTNT/analyst-ratings"
},
Integration with Yahoo’s Website
The analyst ratings powered by the Benzinga API take a prominent position on the Yahoo Finance website, typically appearing on the right sidebar of pages. This strategic placement ensures users can quickly access crucial information while navigating through stock details.
Visual Representation with Graphs
One of the highlights of Yahoo’s implementation is the inclusion of visually appealing graphs alongside analyst ratings. This graphical representation adds depth to the data, allowing users to grasp trends and changes in analyst sentiment over time. The graph on the right sidebar provides an at-a-glance overview, helping users make more informed decisions about their investments.
The chart illustrates the following insights skillfully:
Recommendation Trends: This chart shows the percentage of analysts who recommend buying, holding, selling, or underperforming PYPL stock over time. As of January 19, 2024, 44% of analysts recommend buying the stock, 42% recommend holding it, 10% recommend underperforming it, and 4% recommend selling it.
Recommendation Rating: This chart shows the average recommendation rating for PYPL stock over time. As of January 19, 2024, the average recommendation rating is 2.1, which is bullish.
Analyst Price Targets: This chart shows the average, low, current, and high analyst price targets for PYPL stock. As of January 19, 2024, the average price target is $199.16, the low price target is $159.00, the current price is $186.88, and the high price target is $250.00.
Dedicated Analyst Ratings Page
Yahoo doesn’t stop at just displaying analyst ratings on individual stock pages. They have a dedicated analyst ratings page that aggregates and presents a comprehensive overview of analyst sentiments across multiple stocks. This centralized hub serves as a valuable resource for users who want to explore and compare analyst ratings across various securities in one place.
Dynamic and Real-Time Updates
The integration of the Benzinga Analyst Ratings API ensures that the information presented on Yahoo’s platform is always current and reflects the latest analyst sentiments. This real-time feature is crucial for users who rely on up-to-the-minute data to make timely investment decisions.
User-Friendly Interface
Yahoo’s implementation goes beyond merely displaying raw data. The user interface is designed to be intuitive and user-friendly, making it accessible to a wide range of investors, from beginners to seasoned professionals. The information is presented in a clear and organized manner, ensuring that users can quickly grasp the insights provided by analyst ratings.
We will now try to find out how these charts are made by Yahoo Finance by integrating the analyst data from Benzinga.
Step 1: Extracting Data
The first step here is to get the data from the API and convert it into a human and model-readable format mostly CSV files. For that, we will use Benzinga’s official Python Library and get to the result in a few lines of code elaborated below:
#import libs
from benzinga import financial_data
from benzinga import news_data
import pandas as pd
api_key = "YOUR API KEY"
fin = financial_data.Benzinga(api_key)
ratings = fin.ratings(date_from = '2024-01-01', date_to = '2024-01-31', company_tickers = 'TSLA' )
df = pd.DataFrame(ratings['ratings'])
Let me break down the code and simplify it. In the starting few lines, we are importing the necessary packages into our Python environment. For extracting the data, we just need two packages which are Benzinga’s Python library “benzinga” and “pandas”.
Following that, the next two lines are concerned about activating the API key. Make sure to replace “YOUR API KEY” with your secret Benzinga API key which you can obtain once you create a Benzinga developer account.
Then comes the actual extraction part where we are using the “ratings” function provided by the “benzinga” library to get the analyst ratings data of Tesla from the start to the end of January. The function takes the following as parameters:
- date_from: The starting date of the data
- date_to: The ending date of the data
- company_tickers: The list of stocks we’re interested in getting the data of.
Apart from these, there are some additional parameters but those are not in the scope of this article. Finally, we are converting the JSON response into a Pandas dataframe and the we have an output.
Now that we have a good amount of data to work with, let’s move on to the interesting which is replicating Yahoo Finance’s analyst rating charts. We can now harness the power of frameworks and libraries like ReactJS and ChartJS to understand how Yahoo Finance created these compelling charts from the data.
Step 2: Mapping Values
This step is dedicated to preparing the data for visualization. Yahoo Finance follows a specific system of mapping the values received from the API calls to fit them into their visualization. The following code implements the mapping system of Yahoo Finance:
df['yahoo_rating'] = df['rating_current'].copy()
for i in range(len(df)):
if df['rating_current'][i] == 'Outperform' or df['rating_current'][i] == 'Buy' or df['rating_current'][i] == 'Perform' or df['rating_current'][i] == 'Overweight':
df['yahoo_rating'][i] = 'Buy'
elif df['rating_current'][i] == 'Hold' or df['rating_current'][i] == 'Neutral' or df['rating_current'][i] == 'Equal-Weight':
df['yahoo_rating'][i] = 'Hold'
elif df['rating_current'][i] == 'Underweight' or df['rating_current'][i] == 'Sell' or df['rating_current'][i] == 'Reduce':
df['yahoo_rating'][i] = 'Sell'
In the above code, we are mapping the values in the “rating_current” column to match the mapping system of Yahoo Finance. This helps in re-creating the charts seamlessly.
Step 3: Creating the Stacked Bar Chart
Let’s first understand the purpose of this graph. The main idea of this bar chart is to give a glimpse of the buying/selling sentiment of the stock in a specific month. For example, by looking at the bar for the month of December, the majority is in yellow shade indicating that the traders were leaning toward holding the stock. In contrast to this, the month of November reveals a buying sentiment as the majority of the bar is claimed by the green shade.
Step 3.1: Data Wrangling & Manipulation
Now to replicate this chart, we would need to work on the available data and make some changes to it. The following code implements some data wrangling and data manipulation processes to mold the existing data:
# BAR CHART DATAFRAME
df.date = pd.to_datetime(df.date)
bar_df = df.copy()
bar_df['month'] = df.date.apply(lambda x: x.month)
grouped_df = pd.DataFrame(bar_df.groupby(['month'])['yahoo_rating'
].value_counts())
grouped_df = grouped_df.rename(columns={'yahoo_rating': 'rating_count'})
grouped_df = grouped_df.reset_index()
grouped_df.month = grouped_df.month.map({
1: 'Jan 24',
10: 'Oct 23',
11: 'Nov 23',
12: 'Dec 23',
})
barchart_df = grouped_df.pivot(index='month', columns='yahoo_rating',
values='rating_count').fillna(0)
# BAR CHART DATAFRAME
df.date = pd.to_datetime(df.date)
bar_df = df.copy()
bar_df['month'] = df.date.apply(lambda x: x.month)
grouped_df = pd.DataFrame(bar_df.groupby(['month'])['yahoo_rating'].value_counts())
grouped_df = grouped_df.rename(columns = {'yahoo_rating':'rating_count'})
grouped_df = grouped_df.reset_index()
grouped_df.month = grouped_df.month.map({1:'Jan 24', 10:'Oct 23', 11:'Nov 23', 12:'Dec 23'})
barchart_df = grouped_df.pivot(index = 'month', columns = 'yahoo_rating', values = 'rating_count').fillna(0)
I’m not going to dive deep into the intricacies of the code feature above since there is a lot going on. Here’s the final dataframe that we are going to use for creating the stacked bar chart:
If you’re wondering what these numbers are, they are basically the number of times the analysts have quoted that specific sentiment for the stock. For example, in the month of January, the analysts quoted the “Buy” sentiment 10 times for the stock. In a nutshell, we are going to create a count plot to see the distribution of the stock’s sentiment during specific months.
Step 3.2: Basic Charting
Before moving on to replicating Yahoo Finance’s chart, let’s create a basic version to visualize the data:
plt.style.use('seaborn-v0_8-whitegrid')
barchart_df.plot(kind = 'bar', stacked = True)
The above code uses Python’s matplotlib library to create a basic stacked bar chart that looks like this:
Step 3.3: Replicating Yahoo Finance’s Stacked Bar Chart
Now let’s try to refine the basic chart, customize the theme, and add and remove certain features to match the look of Yahoo Finance’s chart. But with Matplotlib, the task is much more difficult due to its limited customization features. That’s where Plotly comes into the play. Plotly is a highly popular charting module in the Python community. Though its ease of use falls behind Matplotlib, its vast library of customization features makes users forget about it. The following code tries to replicate YF’s stacked bar chart:
fig = px.bar(grouped_df, x = 'month', y = 'rating_count',
color = 'yahoo_rating', text = 'rating_count',
color_discrete_sequence = ["#00c073", "#ffdc48", "#ff333a"],
height = 500, width = 370, labels = {'month':'', 'rating_count':''})
fig.update_yaxes(ticksuffix = " ", showline = False, gridcolor = 'grey')
fig.update_xaxes(ticksuffix = " ", showline = True)
fig.update_layout(plot_bgcolor = 'white', font_family = 'Helvetica',
legend = {'y':0.5}, legend_title_text = '',
title = {'text': '<b>Recommendation Trends</b>', 'x':0})
fig.show()
The code might look a little complicated and confusing but that’s because of the heavy customization we’re performing to match the look of Yahoo Finance’s chart. This is the final output of the code:
Though it’s not exactly the same as Yahoo Finance’s chart, but we are pretty close to it. Since the chart is created using Plotly, it’s also interactive. So it’s pretty safe to say that we re-created the stacked bar chart of Yahoo Finance with a few lines of code in Python.
Conclusion
In conclusion, Yahoo Finance’s integration of the Benzinga Analyst Ratings API is a testament to its commitment to providing users with comprehensive and dynamic financial information. This seamless integration unlocks several benefits for users:
- Visualized data: Easy-to-understand charts and graphs depict trends in analyst sentiment over time, facilitating informed decision-making.
- Dedicated ratings page: Centralized hub for comparing analyst ratings across multiple stocks, offering a holistic view of market sentiment.
- Real-time updates: The API ensures up-to-the-minute information, empowering users to adapt to market shifts based on the latest insights.
- User-friendly interface: Accessible to investors of all experience levels, regardless of their technical expertise.
By using the Benzinga Analyst Ratings API, Yahoo! Finance continues to elevate its platform, placing crucial information at users’ fingertips and empowering them to make informed investment decisions with confidence.