NYC Data Science Academy| Blog
Bootcamps
Lifetime Job Support Available Financing Available
Bootcamps
Data Science with Machine Learning Flagship ๐Ÿ† Data Analytics Bootcamp Artificial Intelligence Bootcamp New Release ๐ŸŽ‰
Free Lesson
Intro to Data Science New Release ๐ŸŽ‰
Find Inspiration
Find Alumni with Similar Background
Job Outlook
Occupational Outlook Graduate Outcomes Must See ๐Ÿ”ฅ
Alumni
Success Stories Testimonials Alumni Directory Alumni Exclusive Study Program
Courses
View Bundled Courses
Financing Available
Bootcamp Prep Popular ๐Ÿ”ฅ Data Science Mastery Data Science Launchpad with Python View AI Courses Generative AI for Everyone New ๐ŸŽ‰ Generative AI for Finance New ๐ŸŽ‰ Generative AI for Marketing New ๐ŸŽ‰
Bundle Up
Learn More and Save More
Combination of data science courses.
View Data Science Courses
Beginner
Introductory Python
Intermediate
Data Science Python: Data Analysis and Visualization Popular ๐Ÿ”ฅ Data Science R: Data Analysis and Visualization
Advanced
Data Science Python: Machine Learning Popular ๐Ÿ”ฅ Data Science R: Machine Learning Designing and Implementing Production MLOps New ๐ŸŽ‰ Natural Language Processing for Production (NLP) New ๐ŸŽ‰
Find Inspiration
Get Course Recommendation Must Try ๐Ÿ’Ž An Ultimate Guide to Become a Data Scientist
For Companies
For Companies
Corporate Offerings Hiring Partners Candidate Portfolio Hire Our Graduates
Students Work
Students Work
All Posts Capstone Data Visualization Machine Learning Python Projects R Projects
Tutorials
About
About
About Us Accreditation Contact Us Join Us FAQ Webinars Subscription An Ultimate Guide to
Become a Data Scientist
    Login
NYC Data Science Acedemy
Bootcamps
Courses
Students Work
About
Bootcamps
Bootcamps
Data Science with Machine Learning Flagship
Data Analytics Bootcamp
Artificial Intelligence Bootcamp New Release ๐ŸŽ‰
Free Lessons
Intro to Data Science New Release ๐ŸŽ‰
Find Inspiration
Find Alumni with Similar Background
Job Outlook
Occupational Outlook
Graduate Outcomes Must See ๐Ÿ”ฅ
Alumni
Success Stories
Testimonials
Alumni Directory
Alumni Exclusive Study Program
Courses
Bundles
financing available
View All Bundles
Bootcamp Prep
Data Science Mastery
Data Science Launchpad with Python NEW!
View AI Courses
Generative AI for Everyone
Generative AI for Finance
Generative AI for Marketing
View Data Science Courses
View All Professional Development Courses
Beginner
Introductory Python
Intermediate
Python: Data Analysis and Visualization
R: Data Analysis and Visualization
Advanced
Python: Machine Learning
R: Machine Learning
Designing and Implementing Production MLOps
Natural Language Processing for Production (NLP)
For Companies
Corporate Offerings
Hiring Partners
Candidate Portfolio
Hire Our Graduates
Students Work
All Posts
Capstone
Data Visualization
Machine Learning
Python Projects
R Projects
About
Accreditation
About Us
Contact Us
Join Us
FAQ
Webinars
Subscription
An Ultimate Guide to Become a Data Scientist
Tutorials
Data Analytics
  • Learn Pandas
  • Learn NumPy
  • Learn SciPy
  • Learn Matplotlib
Machine Learning
  • Boosting
  • Random Forest
  • Linear Regression
  • Decision Tree
  • PCA
Interview by Companies
  • JPMC
  • Google
  • Facebook
Artificial Intelligence
  • Learn Generative AI
  • Learn ChatGPT-3.5
  • Learn ChatGPT-4
  • Learn Google Bard
Coding
  • Learn Python
  • Learn SQL
  • Learn MySQL
  • Learn NoSQL
  • Learn PySpark
  • Learn PyTorch
Interview Questions
  • Python Hard
  • R Easy
  • R Hard
  • SQL Easy
  • SQL Hard
  • Python Easy
Data Science Blog > APIs > Taming News Flow

Taming News Flow

Kamal Sandhu
Posted on Mar 25, 2017

I was born and raised in India and moved to Canada when I was 19. Canada is one of most developed countries in the world. It is a sparsely populated, mature developed economy, mature democracy and a vibrant mix of different ethnicities. India, on the other hand, is a one of the most densely populated large countries in the world and one of the fastest growing major economies. It is also a young democracy and a young nation. Among other things, how these two nations saw the outside world left a marked impression on me and I always had a desire to investigate it further.

Viewpoints, I believe, are shaped as much by the information sources consumed by an individual as they are by priori believes. Our opinions, event knowledge and event interpretation are shaped by what we hear and read. These believes drive us to seek information with a particular bias creating a feedback loop. People with specific believes congregate and start forming (sub)cultures that start seeing the world through their own lens.

It is explainable when two nations on the opposite ends of majority of World Bank tables hold very different viewpoints about outside events. But it becomes perplexing when contrasting interpretations of real world events are held by people living in the same city, those living in the same neighborhood or ones living in the same household. Our lens is defined by whichever information loop we get stuck in. Seeking sources that invalidate our believes generates cognitive dissonance, and seeking sources that validate them stokes our ego via confirmation bias. News organisations are one of the strongest loop propagating mediums and are a perfect source for anyone looking for belief validation.

Being a budding data scientist in training, one simply cannot make statements without attempting to test their validity. As part of this project, I looked at different news sources and tested to see if they systematically bias news reports tried to measure it algorithmically. Questions I was trying to answer: Are there measurable differences between how events are covered by different news organizations? Do different organizations communicate a stronger positive or negative sentiment? Are they talking about different subjects and different people? As we shall see below, answer to all these questions is yes.

Given a short project completion time frame and limited resources, I selected my news sources where there were known biases. Further, I chose Donald Trump as the principal object and analysed news article that mentioned his name.

Given enough time and resources, I would have liked to scrape dozens of news sources from different countries. This would have been accomplished by collating articles written in native languages of different countries, translating them into English and comparing them to native English sources. This would have enabled me to quantitatively measure the bias in news sources by language and would have provided more data to establish differences. But this would have made this projects worthy of a PhD thesis not a 2-week mini-project.

On the advice of my TA and other people, I narrowed down the scope of the project to a few simple questions. (1) Find outlets that have opposite biases from each other. (2) Identify the sentiment they are communicating in the articles. (3) Find out what events and people they are talking about in conjunction with Donald Trump. I chose CNN and Fox as two organizations with opposing biases. Reuters was chosen as the neutral source. Please keep in mind that the main purpose of the project was to scrape data, clean it and present it graphically. This was not a statistical measurement or benchmarking of biases. I decided to take on the NLP portion because I was able to complete the scraping part ahead of schedule.

News articles were scraped for the week of Feb 5th - Feb 12th. This was a week before Michael Flynn stepped down from the position of National Security Adviser. All the articles were dispatched to Google Natural Language Processing API and Textrazor Natural Language Processing API for sentiment analysis.

Code Outline

Project code is parked here. Spiders were deployed in the cloud and scheduled to run every 8 hours. Scraping -

  1. Spider starts at the RSS of each news source.
  2. Clicks through each category and goes to the next page. This page lists of all the articles in this category published in the last 24 hours.
  3. On the article listing page, spider clicks on each article. This takes the crawling spider to the articles page.
  4. It keeps a track of all previously scraped pages and skips them.
  5. Spider copies the title, author, publication time and article text.
  6. A text processing pipelines sends this information to a database.

Sentiment and entity extraction -

  1. Connect and authenticate with all APIโ€™s.
  2. Download one article at a time from the database.
  3. Keep the article if it mentions the entity otherwise dump it and pull the next article.
  4. Clean the text for html tags, unwanted spaces and copyright/disclosure statements.
  5. Save the article in a JSON file using the hash function of article body as the file name.
  6. Check to make sure that this article has not been sent to the language API before.
  7. Send the article to language API#1.
  8. Collect API response and save it in the response data frame.
  9. Send the article to language API#2.
  10. Collect API response and append it to the response data frame.
  11. Write the response dataframe to response JSON file.
  12. Go to step 2 for the next article.

This a sample JSON file that includes the original article and NLP API responses from both the sources.

Data Analysis -

  1. Fetch all JSON files and extract the required information columns from them.
  2. Group as needed.
  3. Produce simple charts.

Results

As stated earlier, for the purpose of this project I narrowed down the analysis to a few specific questions. Letโ€™s go through them one by one. Articles were only scraped for a period of 1 week and all the analysis represents that period.


ArticleLength

Length of articles

CNN tends to write longer articles followed by Fox and Reuters.

I hypothesize that the articles written by Reuters are factual representations of actual events without any commentary or background and hence shorter that other sources. Many of the articles found on Reuters RSS feed represent pure reporting of events.

CNN articles tend to have a lot of html tags embedded in them. The lengths of the articles is calculated after removing these html tags.


How does the sentiment of different news sources compare to each other?ArticleSentiment

NLP sentiment analysis algorithms can classify if the attitude of the writer is positive, neutral or negative.

News sources generally tend to rely on large number of negative stories and some feel good stories to sell themselves. Articles not using either usually fail to sell.

This can be clearly seen when we compare the sentiment of stories published by all three sources. Stories are centered close to the middle but with a negative skew.

 


How does the magnitude of sentiment compare?SentimentMagnitude

We see a fairly stark difference here. We saw in the last chart that overall sentiment of CNN articles is centered around the middle with a negative skew. The chart on right shows that whatever (negative) sentiment CNN is expressing, is being expressed forcefully. This means that they are writing opinionated articles.

Fox News comes in on the second place followed by Reuters. Articles from Reuters on average, do not express strong opinions which falls in line with the original hypothesis of factual reporting.


What entities and topics are news sources covering?

NLP algorithms can extract proper nouns (entity) from a given text. Main entity of an article can be defined as the object of an article. It could be a person, organisation or a legislative unit. Relevance of an entity to an article is defined by its salience score. Higher relevance produces a higher salience score. Topic of the article is categorized in a similar manner.

As the articles were selected based on presence of word Donald Trump, many of them had him as the entity with highest salience. Other entities usually had a lower salience score.

For this part of the analysis, I removed Donald Trump as the entity from the analysis data frame. This left all the other entities behind. These entities were relevant to that article and to him. I picked the top 5 entities in each article and collated them. Then I counted the number of articles for which each of these entities was in top 5. This gave me a list of 18-20 entities that each news source was talking about in conjunction with Donald Trump.


CNNEntitiesGoogle

CNN

Entities most covered by CNN articles related to Donald Trump during this week were US, Elizabeth Warren, Ivanka Trump, Betsy Devos, Michael Flynn, Andrew Puzder and Sean Spicer. Anyone who follows the American politics would agree that the algorithm got it right. Many different politicians related to Donald Trump were in the news. This also shows that CNN was focused on covering people close to and opposing Donald Trump. Other countries or international leaders did not make it to the top of the list. Japanese prime minister Shinzo Abe was visiting US during this week but did not make it to the top of the list.

Topically, CNN focused on the US President, Senate, political CNNTopicsGoogleparties, illegal immigration, politics and Trump family.

Topical distribution means that the entities mentioned in the article were covered in the context of these broad conversations. This breakdown is consistent with the last part.

Looking at both entities and topics gives us a perspective about CNN's main areas of interest.


Fox NewsFoxEntitiesGoogle

Graph on the right shows that more Fox articles mentioned Betsy Devos than US (represents US, United States and United States of America). Republicans, Michael Flynn, Sean Spicer and Steve Bannon were the other entities consistently mentioned in articles.

Elizabeth Warren and Ivanka Trump were 2nd and 3rd entities for CNN but they did not make to the top 6 for Fox News. Steve Bannon makes it to the top 6 for Fox but was not in the CNN list.

Similarly, topical analysis also shows differences between both the FoxTopicsGoogleorganisations. Fox seems to talk more about the Republican Party, politics and Supreme Court as compared to CNN. It is talking relatively less often about the US President and the Trump Family.

Here we start to see some more differences between CNN and Fox. These differences raise a lot of questions. Some of the unanswered questions I have are: Were Fox viewers more concerned about confirmation of Betsy Devos than CNN viewer? Is Supreme Court more important for the Fox viewers than CNN viewers? Is CNN disproportionately focused on the US President?


Reuters

As compared to CNN and Fox, Reuters is geared towards a global audience.ReutersEntitiesGoogle This is clearly seen in the topics covered by them. During this week, Reuters was covering the Chinese, international leaders, comedians, Lady Gaga and the Supreme Court.

This is a clear departure from Fox News/CNN and gives a very clear indication that its articles are targeted towards a different audience.

Combined with neutral and low magnitude sentiment, Reuters stands out from the others.


Future

There are many obvious limitations associated with this project as implemented. This project was only meant to be a data collection and cleaning project. I was able to implement that part of the project fairly quickly and decided to take it a step further and incorporate NLP analysis.

Limited metrics were collected on original data. No analysis was performed to establish statistically significant differences between sentiments and topics covered by different companies.

Possibilities

This project provides a proof of concept for a large scale system and an anecdotal evidence that different news sources might be prioritizing different topics and entities. Visualizations also provide an anecdotal evidence that news sources may be introducing bias into reporting. Possibilities -

  1. Could be easily generalized to measure emotions prevailing in hundreds of sources. This would help get a real-time pulse on the news emotions of the world.
  2. Could be combined with viewership numbers to model the impact of breaking events.
  3. Incorporation of social media feeds.
  4. Resource for research into fake news and extreme ideologies. Tracking of hate speech on news sources and social media.
  5. Bigger net could be cast by incorporating audio, video news sources and YouTube videos using voice recognition capabilities of neural nets.
  6. Listening to public conversations at public places to gauge emotions. This would raise significant moral, ethical and legal hazards.
  7. NSA style phone call monitoring to thwart terrorist attacks.

Project code can be found here. Please get in touch with comments and feedback.

Tools Used

Python, PyCharm, JSON, Pandas, Scrapy, NLTK, Scrapinghub, Crawlera, Google Natural Language Processing API, Textrazor API, R, RStudio, Dplyr, Tidyr, Lubridate, Ggplot, JSONlite

About Author

Kamal Sandhu

Kamal Sandhu is a finance professional keenly interested in the potential of data science in combination with financial and management theory. He is working towards the Chartered Financial Analyst (CFA) program and the Financial Risk Manager (FRM) program....
View all posts by Kamal Sandhu >

Related Articles

Capstone
Catching Fraud in the Healthcare System
Capstone
The Convenience Factor: How Grocery Stores Impact Property Values
Capstone
Acquisition Due Dilligence Automation for Smaller Firms
Machine Learning
Pandemic Effects on the Ames Housing Market and Lifestyle
Machine Learning
The Ames Data Set: Sales Price Tackled With Diverse Models

Leave a Comment

Cancel reply

You must be logged in to post a comment.

No comments found.

View Posts by Categories

All Posts 2399 posts
AI 7 posts
AI Agent 2 posts
AI-based hotel recommendation 1 posts
AIForGood 1 posts
Alumni 60 posts
Animated Maps 1 posts
APIs 41 posts
Artificial Intelligence 2 posts
Artificial Intelligence 2 posts
AWS 13 posts
Banking 1 posts
Big Data 50 posts
Branch Analysis 1 posts
Capstone 206 posts
Career Education 7 posts
CLIP 1 posts
Community 72 posts
Congestion Zone 1 posts
Content Recommendation 1 posts
Cosine SImilarity 1 posts
Data Analysis 5 posts
Data Engineering 1 posts
Data Engineering 3 posts
Data Science 7 posts
Data Science News and Sharing 73 posts
Data Visualization 324 posts
Events 5 posts
Featured 37 posts
Function calling 1 posts
FutureTech 1 posts
Generative AI 5 posts
Hadoop 13 posts
Image Classification 1 posts
Innovation 2 posts
Kmeans Cluster 1 posts
LLM 6 posts
Machine Learning 364 posts
Marketing 1 posts
Meetup 144 posts
MLOPs 1 posts
Model Deployment 1 posts
Nagamas69 1 posts
NLP 1 posts
OpenAI 5 posts
OpenNYC Data 1 posts
pySpark 1 posts
Python 16 posts
Python 458 posts
Python data analysis 4 posts
Python Shiny 2 posts
R 404 posts
R Data Analysis 1 posts
R Shiny 560 posts
R Visualization 445 posts
RAG 1 posts
RoBERTa 1 posts
semantic rearch 2 posts
Spark 17 posts
SQL 1 posts
Streamlit 2 posts
Student Works 1687 posts
Tableau 12 posts
TensorFlow 3 posts
Traffic 1 posts
User Preference Modeling 1 posts
Vector database 2 posts
Web Scraping 483 posts
wukong138 1 posts

Our Recent Popular Posts

AI 4 AI: ChatGPT Unifies My Blog Posts
by Vinod Chugani
Dec 18, 2022
Meet Your Machine Learning Mentors: Kyle Gallatin
by Vivian Zhang
Nov 4, 2020
NICU Admissions and CCHD: Predicting Based on Data Analysis
by Paul Lee, Aron Berke, Bee Kim, Bettina Meier and Ira Villar
Jan 7, 2020

View Posts by Tags

#python #trainwithnycdsa 2019 2020 Revenue 3-points agriculture air quality airbnb airline alcohol Alex Baransky algorithm alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus ames dataset ames housing dataset apartment rent API Application artist aws bank loans beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Best Data Science Bootcamp 2020 Best Ranked Big Data Book Launch Book-Signing bootcamp Bootcamp Alumni Bootcamp Prep boston safety Bundles cake recipe California Cancer Research capstone car price Career Career Day ChatGPT citibike classic cars classpass clustering Coding Course Demo Course Report covid 19 credit credit card crime frequency crops D3.js data data analysis Data Analyst data analytics data for tripadvisor reviews data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization database Deep Learning Demo Day Discount disney dplyr drug data e-commerce economy employee employee burnout employer networking environment feature engineering Finance Financial Data Science fitness studio Flask flight delay football gbm Get Hired ggplot2 googleVis H20 Hadoop hallmark holiday movie happiness healthcare frauds higgs boson Hiring hiring partner events Hiring Partners hotels housing housing data housing predictions housing price hy-vee Income industry Industry Experts Injuries Instructor Blog Instructor Interview insurance italki Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter las vegas airport lasso regression Lead Data Scienctist Lead Data Scientist leaflet league linear regression Logistic Regression machine learning Maps market matplotlib Medical Research Meet the team meetup methal health miami beach movie music Napoli NBA netflix Networking neural network Neural networks New Courses NHL nlp NYC NYC Data Science nyc data science academy NYC Open Data nyc property NYCDSA NYCDSA Alumni Online Online Bootcamp Online Training Open Data painter pandas Part-time performance phoenix pollutants Portfolio Development precision measurement prediction Prework Programming public safety PwC python Python Data Analysis python machine learning python scrapy python web scraping python webscraping Python Workshop R R Data Analysis R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest Ranking recommendation recommendation system regression Remote remote data science bootcamp Scrapy scrapy visualization seaborn seafood type Selenium sentiment analysis sentiment classification Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau teachers team team performance TensorFlow Testimonial tf-idf Top Data Science Bootcamp Top manufacturing companies Transfers tweets twitter videos visualization wallstreet wallstreetbets web scraping Weekend Course What to expect whiskey whiskeyadvocate wildfire word cloud word2vec XGBoost yelp youtube trending ZORI

NYC Data Science Academy

NYC Data Science Academy teaches data science, trains companies and their employees to better profit from data, excels at big data project consulting, and connects trained Data Scientists to our industry.

NYC Data Science Academy is licensed by New York State Education Department.

Get detailed curriculum information about our
amazing bootcamp!

Please enter a valid email address
Sign up completed. Thank you!

Offerings

  • HOME
  • DATA SCIENCE BOOTCAMP
  • ONLINE DATA SCIENCE BOOTCAMP
  • Professional Development Courses
  • CORPORATE OFFERINGS
  • HIRING PARTNERS
  • About

  • About Us
  • Alumni
  • Blog
  • FAQ
  • Contact Us
  • Refund Policy
  • Join Us
  • SOCIAL MEDIA

    ยฉ 2025 NYC Data Science Academy
    All rights reserved. | Site Map
    Privacy Policy | Terms of Service
    Bootcamp Application