From b0e88b1be6931f5731784497fdbae4f168d36720 Mon Sep 17 00:00:00 2001 From: Tom Dunietz <dunietzt@umich.edu> Date: Mon, 22 Apr 2024 15:33:42 -0400 Subject: [PATCH 1/6] qualanalysis --- qualAnalysis.py | 90 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 qualAnalysis.py diff --git a/qualAnalysis.py b/qualAnalysis.py new file mode 100644 index 0000000..6bce780 --- /dev/null +++ b/qualAnalysis.py @@ -0,0 +1,90 @@ +import nltk +from nltk.sentiment.vader import SentimentIntensityAnalyzer +import requests +import logging +import json +from functools import lru_cache + +# Initialize logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +@lru_cache(maxsize=128) +def get_sentiment_score(article): + """ + Function to get sentiment score of a news article using NLTK Vader sentiment analysis. + """ + try: + sid = SentimentIntensityAnalyzer() + sentiment_score = sid.polarity_scores(article)['compound'] + return sentiment_score + except Exception as e: + logger.error("Error getting sentiment score: %s", str(e)) + return 0 + +@lru_cache(maxsize=128) +def get_news_articles(symbol, news_sources, news_api_key): + """ + Function to get news articles related to a given symbol from News API. + """ + try: + url = f'https://newsapi.org/v2/everything?q={symbol}&sources={news_sources}&apiKey={news_api_key}' + response = requests.get(url) + data = response.json() + if 'articles' in data: + articles = [article['description'] for article in data['articles']] + return articles + else: + return [] + except Exception as e: + logger.error("Error getting news articles: %s", str(e)) + return [] + +@lru_cache(maxsize=128) +def get_analyst_recommendations(symbol, api_key): + """ + Function to get analyst recommendations for a given symbol from Alpha Vantage. + """ + try: + url = f'https://www.alphavantage.co/query?function=OVERVIEW&symbol={symbol}&apikey={api_key}' + response = requests.get(url) + data = response.json() + if 'AnalystRating' in data: + return int(data['AnalystRating']) # Convert to int + else: + return 0 + except Exception as e: + logger.error("Error getting analyst recommendations: %s", str(e)) + return 0 + +def get_financial_sentiment(symbol, news_sources, news_api_key, api_key): + """ + Function to compute the overall strength value based on sentiment analysis of news articles and analyst recommendations. + """ + try: + articles = get_news_articles(symbol, news_sources, news_api_key) + if not articles: + logger.warning("No news articles found for symbol %s", symbol) + return 0 + + total_sentiment_score = sum(get_sentiment_score(article) for article in articles) / len(articles) + analyst_recommendations = get_analyst_recommendations(symbol, api_key) + overall_strength = total_sentiment_score + analyst_recommendations + return overall_strength + except Exception as e: + logger.error("Error computing overall strength: %s", str(e)) + return 0 + +if __name__ == "__main__": + try: + # Configuration + company = 'AAPL' # Specify the company symbol + news_sources = 'bbc-news, bloomberg, cnn, reuters' # Specify news sources + news_api_key = 'YOUR_NEWS_API_KEY' + api_key = 'YOUR_ALPHA_VANTAGE_API_KEY' + + # Get overall strength + strength = get_financial_sentiment(company, news_sources, news_api_key, api_key) + print("Overall Strength:", strength) + except Exception as e: + logger.error("Error in main: %s", str(e)) \ No newline at end of file From 40ff898f93e47e77aa16b1d11ccd5611ecac743d Mon Sep 17 00:00:00 2001 From: Tom Dunietz <dunietzt@umich.edu> Date: Mon, 22 Apr 2024 15:41:02 -0400 Subject: [PATCH 2/6] blackschoels --- ....0.0, Culture=neutral, PublicKeyToken=null | 6 +++ black-scholes.py | 38 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 TLD%/AppData/Local/Temp/system-commandline-sentinel-files/dotnet-suggest-registration-git-credential-manager-core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null create mode 100644 black-scholes.py diff --git a/TLD%/AppData/Local/Temp/system-commandline-sentinel-files/dotnet-suggest-registration-git-credential-manager-core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null b/TLD%/AppData/Local/Temp/system-commandline-sentinel-files/dotnet-suggest-registration-git-credential-manager-core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null new file mode 100644 index 0000000..4e9fcae --- /dev/null +++ b/TLD%/AppData/Local/Temp/system-commandline-sentinel-files/dotnet-suggest-registration-git-credential-manager-core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null @@ -0,0 +1,6 @@ +Exception during registration: +System.ComponentModel.Win32Exception (0x80004005): The system cannot find the file specified + at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo) + at System.Diagnostics.Process.Start() + at System.CommandLine.Invocation.Process.StartProcess(String command, String args, String workingDir, Action`1 stdOut, Action`1 stdErr, ValueTuple`2[] environmentVariables) + at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c.<<RegisterWithDotnetSuggest>b__10_1>d.MoveNext() \ No newline at end of file diff --git a/black-scholes.py b/black-scholes.py new file mode 100644 index 0000000..8825d51 --- /dev/null +++ b/black-scholes.py @@ -0,0 +1,38 @@ +import requests +from scipy.stats import norm +from math import log, sqrt, exp + +# Function to fetch real-time stock price from Alpha Vantage API +def get_stock_price(symbol, api_key): + url = f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={symbol}" + response = requests.get(url) + if response.status_code == 200: + data = response.json() + return float(data['Global Quote']['05. price']) + else: + print(f"Failed to fetch stock price for {symbol}.") + return None + +# Function to calculate the Black-Scholes call option price +def black_scholes_call(S, K, r, sigma, T): + d1 = (log(S / K) + (r + 0.5 * sigma**2) * T) / (sigma * sqrt(T)) + d2 = d1 - sigma * sqrt(T) + return S * norm.cdf(d1) - K * exp(-r * T) * norm.cdf(d2) + +# Function to calculate the Black-Scholes put option price +def black_scholes_put(S, K, r, sigma, T): + d1 = (log(S / K) + (r + 0.5 * sigma**2) * T) / (sigma * sqrt(T)) + d2 = d1 - sigma * sqrt(T) + return K * exp(-r * T) * norm.cdf(-d2) - S * norm.cdf(-d1) + +# Example usage +if __name__ == "__main__": + symbol = "AAPL" # Stock symbol + K = 200 # Strike price + r = 0.05 # Risk-free interest rate + sigma = 0.2 # Volatility + T = 1 # Time to expiration (in years) + api_key = "YOUR_API_KEY" # Your Alpha Vantage API key + + S = get_stock_price(symbol, api_key) + \ No newline at end of file From 57508bb3296bfd96aa86030a300e852346ddfb96 Mon Sep 17 00:00:00 2001 From: Tom Dunietz <dunietzt@umich.edu> Date: Mon, 22 Apr 2024 15:53:03 -0400 Subject: [PATCH 3/6] test --- testing.py | 102 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 testing.py diff --git a/testing.py b/testing.py new file mode 100644 index 0000000..fa17663 --- /dev/null +++ b/testing.py @@ -0,0 +1,102 @@ +import unittest +from your_module import black_scholes_call, black_scholes_put, get_sentiment_score, get_stock_price + +class TestBlackScholes(unittest.TestCase): + def test_black_scholes_call(self): + # Test case for call option pricing + S = 100 # Stock price + K = 100 # Strike price + r = 0.05 # Risk-free interest rate + sigma = 0.2 # Volatility + T = 1 # Time to expiration + call_price = black_scholes_call(S, K, r, sigma, T) + self.assertIsNotNone(call_price) + + def test_black_scholes_put(self): + # Test case for put option pricing + S = 100 # Stock price + K = 100 # Strike price + r = 0.05 # Risk-free interest rate + sigma = 0.2 # Volatility + T = 1 # Time to expiration + put_price = black_scholes_put(S, K, r, sigma, T) + self.assertIsNotNone(put_price) + +class TestSentimentAnalysis(unittest.TestCase): + def test_get_sentiment_score(self): + # Test case for sentiment analysis + article = "This is a positive article about the company." + sentiment_score = get_sentiment_score(article) + print("Sentiment Score:", sentiment_score) + self.assertIsNotNone(sentiment_score) + +class TestLiveness(unittest.TestCase): + def test_get_stock_price(self): + # Test case for liveness of get_stock_price function + symbol = "AAPL" # Stock symbol + api_key = "YOUR_API_KEY" # Your Alpha Vantage API key + stock_price = get_stock_price(symbol, api_key) + self.assertIsNotNone(stock_price) + + def test_get_financial_sentiment(self): + # Test case for liveness of get_financial_sentiment function + company = 'AAPL' # Specify the company symbol + news_sources = 'bbc-news, bloomberg, cnn, reuters' # Specify news sources + news_api_key = 'YOUR_NEWS_API_KEY' + api_key = 'YOUR_ALPHA_VANTAGE_API_KEY' + overall_strength = get_financial_sentiment(company, news_sources, news_api_key, api_key) + self.assertIsNotNone(overall_strength) + +if __name__ == '__main__': + unittest.main() +import unittest +from your_module import black_scholes_call, black_scholes_put, get_sentiment_score, get_stock_price + +class TestBlackScholes(unittest.TestCase): + def test_black_scholes_call(self): + # Test case for call option pricing + S = 100 # Stock price + K = 100 # Strike price + r = 0.05 # Risk-free interest rate + sigma = 0.2 # Volatility + T = 1 # Time to expiration + call_price = black_scholes_call(S, K, r, sigma, T) + self.assertIsNotNone(call_price) + + def test_black_scholes_put(self): + # Test case for put option pricing + S = 100 # Stock price + K = 100 # Strike price + r = 0.05 # Risk-free interest rate + sigma = 0.2 # Volatility + T = 1 # Time to expiration + put_price = black_scholes_put(S, K, r, sigma, T) + self.assertIsNotNone(put_price) + +class TestSentimentAnalysis(unittest.TestCase): + def test_get_sentiment_score(self): + # Test case for sentiment analysis + article = "This is a positive article about the company." + sentiment_score = get_sentiment_score(article) + print("Sentiment Score:", sentiment_score) + self.assertIsNotNone(sentiment_score) + +class TestLiveness(unittest.TestCase): + def test_get_stock_price(self): + # Test case for liveness of get_stock_price function + symbol = "AAPL" # Stock symbol + api_key = "YOUR_API_KEY" # Your Alpha Vantage API key + stock_price = get_stock_price(symbol, api_key) + self.assertIsNotNone(stock_price) + + def test_get_financial_sentiment(self): + # Test case for liveness of get_financial_sentiment function + company = 'AAPL' # Specify the company symbol + news_sources = 'bbc-news, bloomberg, cnn, reuters' # Specify news sources + news_api_key = 'YOUR_NEWS_API_KEY' + api_key = 'YOUR_ALPHA_VANTAGE_API_KEY' + overall_strength = get_financial_sentiment(company, news_sources, news_api_key, api_key) + self.assertIsNotNone(overall_strength) + +if __name__ == '__main__': + unittest.main() From 690aace10f6a7f41a600061e52e18a546885d67e Mon Sep 17 00:00:00 2001 From: dunietzt <71984721+dunietzt@users.noreply.github.com> Date: Mon, 22 Apr 2024 16:03:38 -0400 Subject: [PATCH 4/6] Update testing.py --- testing.py | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/testing.py b/testing.py index fa17663..ea27647 100644 --- a/testing.py +++ b/testing.py @@ -34,17 +34,15 @@ class TestLiveness(unittest.TestCase): def test_get_stock_price(self): # Test case for liveness of get_stock_price function symbol = "AAPL" # Stock symbol - api_key = "YOUR_API_KEY" # Your Alpha Vantage API key - stock_price = get_stock_price(symbol, api_key) + + stock_price = get_stock_price(symbol) self.assertIsNotNone(stock_price) def test_get_financial_sentiment(self): # Test case for liveness of get_financial_sentiment function company = 'AAPL' # Specify the company symbol news_sources = 'bbc-news, bloomberg, cnn, reuters' # Specify news sources - news_api_key = 'YOUR_NEWS_API_KEY' - api_key = 'YOUR_ALPHA_VANTAGE_API_KEY' - overall_strength = get_financial_sentiment(company, news_sources, news_api_key, api_key) + overall_strength = get_financial_sentiment(company, news_sources) self.assertIsNotNone(overall_strength) if __name__ == '__main__': @@ -85,17 +83,16 @@ class TestLiveness(unittest.TestCase): def test_get_stock_price(self): # Test case for liveness of get_stock_price function symbol = "AAPL" # Stock symbol - api_key = "YOUR_API_KEY" # Your Alpha Vantage API key - stock_price = get_stock_price(symbol, api_key) + + stock_price = get_stock_price(symbol) self.assertIsNotNone(stock_price) def test_get_financial_sentiment(self): # Test case for liveness of get_financial_sentiment function company = 'AAPL' # Specify the company symbol news_sources = 'bbc-news, bloomberg, cnn, reuters' # Specify news sources - news_api_key = 'YOUR_NEWS_API_KEY' - api_key = 'YOUR_ALPHA_VANTAGE_API_KEY' - overall_strength = get_financial_sentiment(company, news_sources, news_api_key, api_key) + + overall_strength = get_financial_sentiment(company, news_sources) self.assertIsNotNone(overall_strength) if __name__ == '__main__': From 3adc92a9adf994f13e125a7c7f9f0556cb115a6b Mon Sep 17 00:00:00 2001 From: dunietzt <71984721+dunietzt@users.noreply.github.com> Date: Mon, 22 Apr 2024 16:08:18 -0400 Subject: [PATCH 5/6] Update qualAnalysis.py --- qualAnalysis.py | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/qualAnalysis.py b/qualAnalysis.py index 6bce780..04459dc 100644 --- a/qualAnalysis.py +++ b/qualAnalysis.py @@ -23,12 +23,12 @@ def get_sentiment_score(article): return 0 @lru_cache(maxsize=128) -def get_news_articles(symbol, news_sources, news_api_key): +def get_news_articles(symbol, news_sources): """ Function to get news articles related to a given symbol from News API. """ try: - url = f'https://newsapi.org/v2/everything?q={symbol}&sources={news_sources}&apiKey={news_api_key}' + url = f'https://newsapi.org/v2/everything?q={symbol}&sources={news_sources}' response = requests.get(url) data = response.json() if 'articles' in data: @@ -41,12 +41,12 @@ def get_news_articles(symbol, news_sources, news_api_key): return [] @lru_cache(maxsize=128) -def get_analyst_recommendations(symbol, api_key): +def get_analyst_recommendations(symbol): """ Function to get analyst recommendations for a given symbol from Alpha Vantage. """ try: - url = f'https://www.alphavantage.co/query?function=OVERVIEW&symbol={symbol}&apikey={api_key}' + url = f'https://www.alphavantage.co/query?function=OVERVIEW&symbol={symbol}' response = requests.get(url) data = response.json() if 'AnalystRating' in data: @@ -57,18 +57,18 @@ def get_analyst_recommendations(symbol, api_key): logger.error("Error getting analyst recommendations: %s", str(e)) return 0 -def get_financial_sentiment(symbol, news_sources, news_api_key, api_key): +def get_financial_sentiment(symbol, news_sources): """ Function to compute the overall strength value based on sentiment analysis of news articles and analyst recommendations. """ try: - articles = get_news_articles(symbol, news_sources, news_api_key) + articles = get_news_articles(symbol, news_sources) if not articles: logger.warning("No news articles found for symbol %s", symbol) return 0 total_sentiment_score = sum(get_sentiment_score(article) for article in articles) / len(articles) - analyst_recommendations = get_analyst_recommendations(symbol, api_key) + analyst_recommendations = get_analyst_recommendations(symbol) overall_strength = total_sentiment_score + analyst_recommendations return overall_strength except Exception as e: @@ -80,11 +80,9 @@ def get_financial_sentiment(symbol, news_sources, news_api_key, api_key): # Configuration company = 'AAPL' # Specify the company symbol news_sources = 'bbc-news, bloomberg, cnn, reuters' # Specify news sources - news_api_key = 'YOUR_NEWS_API_KEY' - api_key = 'YOUR_ALPHA_VANTAGE_API_KEY' # Get overall strength - strength = get_financial_sentiment(company, news_sources, news_api_key, api_key) + strength = get_financial_sentiment(company, news_sources) print("Overall Strength:", strength) except Exception as e: - logger.error("Error in main: %s", str(e)) \ No newline at end of file + logger.error("Error in main: %s", str(e)) From efba43474e0161cea05d8d6cc56fc345ccec9db6 Mon Sep 17 00:00:00 2001 From: dunietzt <71984721+dunietzt@users.noreply.github.com> Date: Mon, 22 Apr 2024 16:09:01 -0400 Subject: [PATCH 6/6] Update black-scholes.py --- black-scholes.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/black-scholes.py b/black-scholes.py index 8825d51..a6d7305 100644 --- a/black-scholes.py +++ b/black-scholes.py @@ -3,7 +3,7 @@ from math import log, sqrt, exp # Function to fetch real-time stock price from Alpha Vantage API -def get_stock_price(symbol, api_key): +def get_stock_price(symbol): url = f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={symbol}" response = requests.get(url) if response.status_code == 200: @@ -32,7 +32,7 @@ def black_scholes_put(S, K, r, sigma, T): r = 0.05 # Risk-free interest rate sigma = 0.2 # Volatility T = 1 # Time to expiration (in years) - api_key = "YOUR_API_KEY" # Your Alpha Vantage API key - S = get_stock_price(symbol, api_key) - \ No newline at end of file + + S = get_stock_price(symbol) +