Repository: KVignesh122/AssetNewsSentimentAnalyzer
Branch: main
Commit: b3dcb02333c0
Files: 12
Total size: 37.2 KB
Directory structure:
gitextract_03kt3su7/
├── .gitignore
├── LICENSE
├── MANIFEST.in
├── README.md
├── asset_sentiment_analyzer/
│ ├── __init__.py
│ ├── apps.py
│ ├── gpt_client.py
│ ├── scrapper.py
│ ├── utils.py
│ └── websearch_funcs.py
├── requirements.txt
└── setup.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
.google-cookie
__pycache__/google1.cpython-311.pyc
__pycache__/gpt_client.cpython-311.pyc
__pycache__/scrapper.cpython-311.pyc
__pycache__/websearch.cpython-311.pyc
__pycache__/*
*.csv
oai.py
main-mine.py
websearch copy.py
plotting.py
sbc.py
*.pyc
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: MANIFEST.in
================================================
include LICENSE
include requirements.txt
================================================
FILE: README.md
================================================
# Asset News Sentiment Analyzer
This application provides two sophisticated tools catering to sentiment analysis of financial assets and securities by using ChatGPT on Google search results and online news articles. You will just need an OpenAI API Key to get started and utilize the power of all the functionalities provided by this package, namely to fetch news articles, analyze their content, and produce insightful reports for investment and trading decisions.
A simple trading strategy involving daily sentiment analysis signals from this package may provide basic market traction of the target asset (We did a sample backtest on commodities over the past 100 market days):
<table>
<tr>
<td align="center">
<strong>Crude Oil 100 Days</strong><br>
<img src="images/Crude Oil.jpg" alt="Crude Oil Sample" width="500" height="300">
</td>
<td align="center">
<strong>Gold 100 Days</strong><br>
<img src="images/Gold.jpg" alt="Gold Sample" width="500" height="300">
</td>
</tr>
</table>
***Disclaimer: All investments and trading involve risk. This package is intended for research/academic purposes, and coding projects. It aids algorithmic/quantitative traders and researchers in their work. The reports and signals generated by this package does not constitute financial advice, and users should perform their own due diligence before making any trading decisions.***
## Contents
- [Two Main Classes](#two-main-classes)
- [SentimentAnalyzer Tool](#1-sentimentanalyzer-tool)
- [WebInteractor Tool](#2-webinteractor-tool)
- [Installation](#installation)
- [Contributing](#contributing)
- [License](#license)
## Two Main Classes
### 1. SentimentAnalyzer Tool
The `SentimentAnalyzer` class allows users to perform sentiment analysis on news articles related to a specific financial asset for any given date. It fetches news links, retrieves the content, and if desired, uses GPT models to generate reports and assess market sentiment.
**Usage**
```python
from asset_sentiment_analyzer import SentimentAnalyzer
# Initialize the analyzer
analyzer = SentimentAnalyzer(asset='Crude Oil', openai_key='your-openai-key')
# Get sentiment analysis as string for today or any date in the past (returns "bullish", "bearish", or "neutral")
sentiment = analyzer.get_sentiment(date='06-02-2024')
print(f"The sentiment for the asset is: {sentiment}")
# Fetch news links for any date with news_date argument in MM-dd-YYYY format.
news_links = analyzer.fetch_news_links(news_date='06-02-2024')
# Display news content
for url in news_links:
print(analyzer.show_news_content(url))
# Generate a report
report = analyzer.produce_daily_report(date='06-02-2024', max_words=300)
print(report)
```
**API Reference**
* `SentimentAnalyzer(<asset_name>)`: Initializes the SentimentAnalyzer object with specified asset and optional OpenAI key (`openai_key` parameter) and model selection (`model` parameter).
__Available Methods:__
* `.fetch_news_links()`: Fetches news links from Google Search News tab for the specified asset on the given date. If `news_date` parameter is not assigned, it will retrieve the current day's latests news links. `nlinks` parameter denotes the number of news links to retrieve, default is `4`.
* `.show_news_content(<news_url>)`: Parses and returns main content as string for a given news URL.
* `.get_sentiment()`: Analyzes online results automatically and returns the news sentiment for asset/security on any given date. If `date` parameter is not assigned, it will return the current day's latest sentiment verdict.
* `.produce_daily_report()`: Generates a daily report returned as string with insights based on the online Google Search content for any given date. If `date` parameter is not assigned, it will generate report for the current day. The default `max_words` is `100`, but this can be adjusted as preferred.
Note: All dates must be in `MM-dd-YYYY` format or must be passed as a `datetime.datetime` object into the methods.
### 2. WebInteractor Tool
The `WebInteractor` class provides functionalities to interact with web content, perform Google searches, and retrieve content, which can then be fed into a GPT client for further interaction.
**Usage**
```python
from asset_sentiment_analyzer import WebInteractor
# Initialize the WebInteractor
web_interactor = WebInteractor()
# Perform a Google search and retrieve result links as list
search_results = web_interactor.search_google(query="Apple Stocks", nlinks=5)
print(search_results)
# Fetch the main content of a webpage
content = web_interactor.get_webpage_main_content(url="https://example.com")
print(content)
# Interact with a GPT model
my_prompt = f"""
How will this affect the latest Apple earnings report:
{content}
"""
response = web_interactor.get_llm_response(prompt=my_prompt, openai_api_key="your_openai_api_key")
print(response)
```
**API Reference**
* `WebInteractor()`: Initializes a WebInteractor object which provides functionalities for interacting with web content and performing web searches.
__Available Methods:__
* `.search_google(<query>)`: Searches Google for the specified query and retrieves a list of unique links. Parameters:
* `query` (str): The search query.
* `tld` (str, optional): The top-level domain for Google (eg. 'com' for Google.com).
* `lang` (str, optional): The language setting for the Google search.
* `date` (str, optional): The date to refine search results. (`MM-dd-YYYY` format)
* `country` (str, optional): The country setting for Google search results.
* `tab` (str, optional): Specifies the tab under which the search is performed, allowing for specific types of search results.
* Possible values include:
- `'app'` for Applications
- `'blg'` for Blogs
- `'bks'` for Books
- `'dsc'` for Discussions
- `'isch'` for Images
- `'nws'` for News
- `'pts'` for Patents
- `'plcs'` for Places
- `'rcp'` for Recipes
- `'shop'` for Shopping
- `'vid'` for Video
* `nlinks` (int, optional): The number of links to retrieve.
* `.get_webpage_main_content(<url>)`: Fetches the main content of a webpage.
* `.get_llm_response(<prompt>, <openai_api_key>)`: A method to interact with a GPT language model based on a specified prompt and retrieve its response.
## Installation
Project has been published on pip
```bash
pip install asset-sentiment-analyzer
```
## Contributing
If you would like to contribute to this project, please follow the guidelines below:
- Fork the repository.
- Create a new branch (git checkout -b feature-branch).
- Make your changes.
- Commit your changes (git commit -m 'Add new feature').
- Push to the branch (git push origin feature-branch).
- Open a pull request.
## License
This project is pioneered by SkyBlue Capital (Singapore), and is licensed under the Apache-2.0 License. See the LICENSE file for details.
<img src="images/HBlack.png" alt="SBC Logo" width="190" height="55">
================================================
FILE: asset_sentiment_analyzer/__init__.py
================================================
from . import gpt_client
from . import scrapper
from . import utils
from . import websearch_funcs
from .apps import SentimentAnalyzer, WebInteractor
__all__ = [SentimentAnalyzer, WebInteractor, websearch_funcs, gpt_client, scrapper, utils]
================================================
FILE: asset_sentiment_analyzer/apps.py
================================================
import asyncio
from . import websearch_funcs
from .scrapper import get_news_links, parse_webpage
from datetime import datetime
from .gpt_client import chunk, get_gpt_response, ANALYSER_INSTR
class SentimentAnalyzer:
def __init__(self, asset, openai_key=None, model="gpt-3.5-turbo") -> None:
"""
Initializes the SentimentAnalyzer object.
Parameters:
asset (str): The financial asset for which sentiment analysis is to be performed.
openai_key (str, optional): The API key for OpenAI, required for accessing GPT models.
model (str, optional): The specific GPT model to use for generating text and analyzing sentiment.
Returns:
None
"""
self.asset = asset
self.oai_key = openai_key
self.model = model
self.date_of_interest = None
self.news_links = None
return
def fetch_news_links(self, news_date=datetime.today(), nlinks=4):
"""
Fetches a specific number of news links related to the asset on a given date.
Parameters:
news_date (datetime, optional): The date for which to fetch news links.
nlinks (int, optional): The maximum number of news links to retrieve.
Returns:
list: A list of URLs as strings that link to news articles.
Raises:
ValueError: If 'nlinks' is not an integer.
"""
if not isinstance(nlinks, int):
raise ValueError("nlinks parameter value has to be an int.")
if news_date == self.date_of_interest:
assert(self.news_links is not None)
return self.news_links
self.news_links = get_news_links(self.asset, nlinks, news_date)
self.date_of_interest = news_date
return self.news_links
def show_news_content(self, news_url):
"""
Fetches and displays the content of a news article from a URL.
Parameters:
news_url (str): The URL of the news article to fetch content from.
Returns:
str: The content of the news article.
"""
return asyncio.run(parse_webpage(news_url))
async def __get_all_news_content(self, links):
"""
Asynchronously retrieves and concatenates the content from a list of news URLs.
Parameters:
links (list): A list of news URLs to fetch content from.
Returns:
str: Concatenated content from all the news articles.
"""
news = ''
for idx, link in enumerate(links, start=1):
news += f"""
Article {idx}:
"{await parse_webpage(link)}"
"""
return news
def __construct_report_prompt(self, max_words, news):
return f"""Write out a short and impactful report with key insights
for {self.asset} from these given information:
{news}
Your writeup must strictly be within {max_words} words.
"""
def produce_daily_report(self, date=datetime.today(), max_words=100):
"""
Produces a short report based on the news linked to the asset for given date, using the GPT model.
Parameters:
date (datetime, optional): The date for which the report is produced.
max_words (int, optional): The maximum number of words in the report.
Returns:
str: The generated report as a string.
Raises:
ValueError: If an OpenAI API key is not set.
"""
if self.oai_key is None:
raise ValueError("An OpenAI API key is required to interact with GPT models.")
links = self.fetch_news_links(date)
news = asyncio.run(self.__get_all_news_content(links))
news = chunk(news)
text = get_gpt_response(
user_prompt=self.__construct_report_prompt(max_words, news),
openai_key=self.oai_key,
preferred_model=self.model
)
return text
def __construct_sentiment_prompt(self, news):
return f"""Based on all your knowlege of financial markets and textual analysis,
assess information from all these articles and determine if the sentiment for {self.asset}
is mainly bullish, bearish, or neutral:
{news}
Your response must strictly contain only one word string in lower case ("bullish", "bearish",
or "neutral") and no other words.
"""
def get_sentiment(self, date=datetime.today()):
"""
Determines the news sentiment for the asset for the given date, using the GPT model.
Parameters:
date (datetime, optional): The date for which sentiment is assessed.
Returns:
str: The determined sentiment ('bullish', 'bearish', or 'neutral').
Raises:
ValueError: If an OpenAI API key is not set.
"""
if self.oai_key is None:
raise ValueError("An OpenAI API key is required to interact with GPT models.")
links = self.fetch_news_links(date)
assert(len(links) <= 4)
news = asyncio.run(self.__get_all_news_content(links))
news = chunk(news)
sentiment = get_gpt_response(
user_prompt=self.__construct_sentiment_prompt(news),
openai_key=self.oai_key,
generation_tk_limit=10,
preferred_model=self.model,
system_instruction=ANALYSER_INSTR
)
return sentiment.lower()
class WebInteractor():
def __init__(self) -> None:
"""
Initializes the WebInteractor class which provides functionalities
for interacting with web content and performing web searches.
"""
pass
def search_google(self, query, tld='com', lang='en', date='0', country='', tab='', nlinks=None):
"""
Searches Google for the specified query and retrieves a list of unique links.
Parameters:
query (str): The search query.
tld (str, optional): The top-level domain for Google (e.g., 'com' for Google.com).
lang (str, optional): The language setting for the Google search.
date (str, optional): The date to refine search results.
country (str, optional): The country setting for Google search results.
tab (str, optional): Specifies the tab under which the search is performed, allowing for specific types of search results.
Possible values include:
- 'app' for Applications
- 'blg' for Blogs
- 'bks' for Books
- 'dsc' for Discussions
- 'isch' for Images
- 'nws' for News
- 'pts' for Patents
- 'plcs' for Places
- 'rcp' for Recipes
- 'shop' for Shopping
- 'vid' for Video
nlinks (int, optional): The number of links to retrieve.
Returns:
list: A unique set of URLs returned from the Google search.
"""
links = list(websearch_funcs.search_google(
query=query,
tld=tld,
lang=lang,
tbs=websearch_funcs.get_tbs(date),
country=country,
tbm=tab,
stop=nlinks
))
return list(set(links))
def get_webpage_main_content(self, url):
return asyncio.run(parse_webpage(url))
def get_llm_response(self, prompt, openai_api_key, generation_tk_limit=None, gpt_model="gpt-3.5-turbo", system_instruction=None):
"""
Generates a response from a GPT language model based on a specified prompt.
Parameters:
prompt (str): The prompt to send to the language model.
openai_api_key (str): The API key for OpenAI, required for accessing the language model.
generation_tk_limit (int, optional): The maximum number of tokens that the language model is allowed to generate.
gpt_model (str, optional): The specific GPT model to use for generating responses.
system_instruction (str, optional): Additional instructions to guide the language model's response.
Returns:
str: The response generated by the language model for the user query.
"""
return get_gpt_response(
user_prompt=prompt,
openai_key=openai_api_key,
generation_tk_limit=generation_tk_limit,
preferred_model=gpt_model,
system_instruction=system_instruction
)
================================================
FILE: asset_sentiment_analyzer/gpt_client.py
================================================
from openai import OpenAI
import tiktoken
ENCODING_STANDARD = "cl100k_base"
ANALYSER_INSTR = """You will be provided with a few financial/technical analysis writeups,
news content, or opinion articles by the user. Based on these content, determine if the asset
being requested by the user has a overall bullish, bearish, or neutral sentiment. Follow the instructions
of the user closely.
"""
def get_tokens(text: str):
enc = tiktoken.get_encoding(ENCODING_STANDARD)
return enc.encode(text)
def get_token_length(text: str):
return len(get_tokens(text))
def decode_tokens(tokens):
enc = tiktoken.get_encoding(ENCODING_STANDARD)
return enc.decode(tokens)
def chunk(text: str, max_token_len=3000):
text_tk_length = get_token_length(text)
if text_tk_length > max_token_len:
tokenized_text = get_tokens(text)
return decode_tokens(tokenized_text[:max_token_len])
return text
def get_gpt_response(user_prompt: str, openai_key: str, generation_tk_limit=None, preferred_model="gpt-3.5-turbo", system_instruction=None):
client = OpenAI(api_key=openai_key)
if system_instruction is not None:
gpt_prompt = [
{"role":"system","content": system_instruction},
{"role": "user", "content": user_prompt}
]
else:
gpt_prompt = [
{"role": "user", "content": user_prompt}
]
response = client.chat.completions.create(
model=preferred_model,
messages=gpt_prompt,
max_tokens=generation_tk_limit
)
return response.choices[0].message.content
================================================
FILE: asset_sentiment_analyzer/scrapper.py
================================================
from bs4 import BeautifulSoup
from readability import Document
from .websearch_funcs import search_google, get_tbs
import aiohttp
import asyncio
from .utils import get_random_user_agent
async def fetch(session, url):
headers = {'User-Agent': get_random_user_agent()}
try:
timeout = aiohttp.ClientTimeout(total=60) # Increasing the total timeout to 60 seconds
await asyncio.sleep(0.5)
async with session.get(url, headers=headers, timeout=timeout) as response:
return await response.text()
except aiohttp.ClientError as e:
print(f"Client error: {e}")
return None
except asyncio.TimeoutError:
print("The request timed out")
return None
async def parse_webpage(url_link):
async with aiohttp.ClientSession() as session:
html_content = await fetch(session, url_link)
if html_content is not None:
doc = Document(html_content)
soup = BeautifulSoup(doc.summary(), 'html.parser')
return soup.get_text(strip=True)
return ''
def get_news_links(asset_name: str, nlinks: int, date=None) -> list:
links = []
additional_queries = [
asset_name + " technical analysis",
asset_name + " price sentiment",
asset_name + " trading signal",
asset_name,
]
i = 0
while len(links) < nlinks and i <= 3:
articles_needed = nlinks - len(links)
if date:
links += list(search_google(additional_queries[i], stop=articles_needed, pause=0.5, tbm="nws", tbs=get_tbs(date)))
else:
links += list(search_google(additional_queries[i], stop=articles_needed, pause=0.5, tbm="nws"))
links = list(set(links))
i += 1
return links
================================================
FILE: asset_sentiment_analyzer/utils.py
================================================
from random import choice
# List of user agents for requests
USER_AGENTS_LIST = [
# Chrome
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36',
# Firefox
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:88.0) Gecko/20100101 Firefox/88.0',
'Mozilla/5.0 (X11; Linux x86_64; rv:88.0) Gecko/20100101 Firefox/88.0',
# Safari
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1 Safari/605.1.15',
'Mozilla/5.0 (iPhone; CPU iPhone OS 14_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1',
# Edge
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36 Edg/90.0.818.49',
# Opera
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36 OPR/76.0.4017.123'
]
# Define URL templates
GOOGLE_HOMEPAGE_URL = "https://www.google.%(tld)s/"
GOOGLE_SEARCH_RESULTS_URL = "https://www.google.%(tld)s/search?hl=%(lang)s&q=%(query)s&" \
"btnG=Google+Search&tbs=%(tbs)s&safe=%(safe)s&" \
"cr=%(country)s&tbm=%(tbm)s"
def get_random_user_agent():
"""Select a random user agent from a predefined list."""
return choice(USER_AGENTS_LIST)
================================================
FILE: asset_sentiment_analyzer/websearch_funcs.py
================================================
import os
import time
import ssl
from http.cookiejar import LWPCookieJar
from urllib.request import Request, urlopen
from urllib.parse import quote_plus, urlparse, parse_qs
from bs4 import BeautifulSoup
from datetime import datetime, date
from . import utils
# Initialize cookie jar at script directory
current_folder = os.path.dirname(os.path.abspath(__file__))
cookie_jar_path = os.path.join(current_folder, '.google-cookie')
cookie_jar = LWPCookieJar(cookie_jar_path)
try:
cookie_jar.load()
except Exception:
pass # Handle exceptions or log errors as needed
def get_tbs(preferred_date):
"""Format the tbs parameter for Google search."""
if preferred_date == '0':
return '0'
preferred_date = to_date(preferred_date)
if is_future_date(preferred_date):
raise ValueError(f"Cannot be a future date.")
date_str = preferred_date.strftime('%m/%d/%Y')
return f"cdr:1,cd_min:{date_str},cd_max:{date_str}"
def to_date(input_date):
"""
Convert a datetime.datetime object or a string containing a date
into a datetime.date object.
:param input_date: A datetime.datetime object or a string representing a date.
:param date_format: A string representing the expected format of the date string (optional).
:return: A datetime.date object.
"""
if isinstance(input_date, datetime):
return input_date.date()
elif isinstance(input_date, str):
try:
return datetime.strptime(input_date, '%m/%d/%Y').date()
except ValueError:
raise ValueError(f"Date string does not match format '%m/%d/%Y'")
else:
raise TypeError("Input must be a datetime.datetime object or a string")
def is_future_date(input_date):
"""
Check if a given datetime.date object is a date in the future.
:param input_date: A datetime.date object.
:return: True if the input_date is in the future, False otherwise.
"""
if not isinstance(input_date, date) and not isinstance(input_date, datetime):
raise TypeError("Input date must be a datetime.date object")
today = date.today()
return input_date > today
def get_page(url, user_agent=None, verify_ssl=True):
"""Retrieve a webpage with optional SSL verification."""
if user_agent is None:
user_agent = utils.get_random_user_agent()
request = Request(url, headers={'User-Agent': user_agent})
cookie_jar.add_cookie_header(request)
context = ssl.create_default_context() if verify_ssl else ssl._create_unverified_context()
response = urlopen(request, context=context)
cookie_jar.extract_cookies(response, request)
html_content = response.read()
response.close()
try:
cookie_jar.save()
except Exception:
pass
return html_content
def filter_result(link):
"""Filter valid links from Google search results."""
if link.startswith('/url?'):
link = parse_qs(urlparse(link).query)['q'][0]
o = urlparse(link)
if o.netloc and 'google' not in o.netloc:
return link
def search_google(query, tld='com', lang='en', tbs='0', safe='off',
stop=None, pause=1.0, country='', tbm='', user_agent=None):
"""Perform a Google search and yield found URLs."""
query = quote_plus(query)
initial_url = utils.GOOGLE_HOMEPAGE_URL % vars()
get_page(initial_url, user_agent)
results = set()
count = 0
while not stop or count < stop:
time.sleep(pause) # Pause to avoid rate limiting
search_url = utils.GOOGLE_SEARCH_RESULTS_URL % vars()
html = get_page(search_url, user_agent)
soup = BeautifulSoup(html, 'html.parser')
anchors = soup.find(id='search').find_all('a') if soup.find(id='search') else soup.find_all('a')
for anchor in anchors:
link = anchor.get('href')
if link and (filtered_link := filter_result(link)) and filtered_link not in results:
results.add(filtered_link)
yield filtered_link
count += 1
if stop and count >= stop:
break
if count == len(results):
break
================================================
FILE: requirements.txt
================================================
requests
beautifulsoup4
readability-lxml
lxml_html_clean
tiktoken
openai
aiohttp
================================================
FILE: setup.py
================================================
from setuptools import setup, find_packages
setup(
name='asset_sentiment_analyzer',
version='0.1.4',
description='A sentiment analyzer package for financial assets and securities utilizing GPT models.',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
url='https://github.com/KVignesh122/AssetNewsSentimentAnalyzer',
author='Kumaravel Vignesh',
author_email='k_vignesh@hotmail.com',
license='Apache-2.0',
packages=find_packages(),
install_requires=open('requirements.txt').read().splitlines(),
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10'
],
python_requires='>=3.6',
)
gitextract_03kt3su7/ ├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.md ├── asset_sentiment_analyzer/ │ ├── __init__.py │ ├── apps.py │ ├── gpt_client.py │ ├── scrapper.py │ ├── utils.py │ └── websearch_funcs.py ├── requirements.txt └── setup.py
Condensed preview — 12 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (40K chars).
[
{
"path": ".gitignore",
"chars": 248,
"preview": ".google-cookie\n__pycache__/google1.cpython-311.pyc\n__pycache__/gpt_client.cpython-311.pyc\n__pycache__/scrapper.cpython-3..."
},
{
"path": "LICENSE",
"chars": 11357,
"preview": " Apache License\n Version 2.0, January 2004..."
},
{
"path": "MANIFEST.in",
"chars": 41,
"preview": "include LICENSE\ninclude requirements.txt\n"
},
{
"path": "README.md",
"chars": 6972,
"preview": "# Asset News Sentiment Analyzer\n\nThis application provides two sophisticated tools catering to sentiment analysis of fin..."
},
{
"path": "asset_sentiment_analyzer/__init__.py",
"chars": 242,
"preview": "from . import gpt_client\nfrom . import scrapper\nfrom . import utils\nfrom . import websearch_funcs\n\nfrom .apps import Sen..."
},
{
"path": "asset_sentiment_analyzer/apps.py",
"chars": 8890,
"preview": "import asyncio\nfrom . import websearch_funcs\n\nfrom .scrapper import get_news_links, parse_webpage\nfrom datetime import d..."
},
{
"path": "asset_sentiment_analyzer/gpt_client.py",
"chars": 1594,
"preview": "from openai import OpenAI\nimport tiktoken\n\nENCODING_STANDARD = \"cl100k_base\"\nANALYSER_INSTR = \"\"\"You will be provided wi..."
},
{
"path": "asset_sentiment_analyzer/scrapper.py",
"chars": 1774,
"preview": "from bs4 import BeautifulSoup\nfrom readability import Document\nfrom .websearch_funcs import search_google, get_tbs\nimpor..."
},
{
"path": "asset_sentiment_analyzer/utils.py",
"chars": 1707,
"preview": "from random import choice\n\n# List of user agents for requests\nUSER_AGENTS_LIST = [\n # Chrome\n 'Mozilla/5.0 (Window..."
},
{
"path": "asset_sentiment_analyzer/websearch_funcs.py",
"chars": 4203,
"preview": "import os\nimport time\nimport ssl\nfrom http.cookiejar import LWPCookieJar\nfrom urllib.request import Request, urlopen\nfro..."
},
{
"path": "requirements.txt",
"chars": 80,
"preview": "requests\nbeautifulsoup4\nreadability-lxml\nlxml_html_clean\ntiktoken\nopenai\naiohttp"
},
{
"path": "setup.py",
"chars": 978,
"preview": "from setuptools import setup, find_packages\n\nsetup(\n name='asset_sentiment_analyzer',\n version='0.1.4',\n descri..."
}
]
About this extraction
This page contains the full source code of the KVignesh122/AssetNewsSentimentAnalyzer GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 12 files (37.2 KB), approximately 8.8k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.