From the uDemy course on LLM engineering.
https://www.udemy.com/course/llm-engineering-master-ai-and-large-language-models
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
297 lines
11 KiB
297 lines
11 KiB
{ |
|
"cells": [ |
|
{ |
|
"cell_type": "markdown", |
|
"id": "306f1a67-4f1c-4aed-8f80-2a8458a1bce5", |
|
"metadata": {}, |
|
"source": [ |
|
"# Stock data analysis" |
|
] |
|
}, |
|
{ |
|
"cell_type": "code", |
|
"execution_count": 1, |
|
"id": "4e2a9393-7767-488e-a8bf-27c12dca35bd", |
|
"metadata": {}, |
|
"outputs": [], |
|
"source": [ |
|
"import os\n", |
|
"import requests\n", |
|
"from dotenv import load_dotenv\n", |
|
"from bs4 import BeautifulSoup\n", |
|
"from IPython.display import Markdown, display\n", |
|
"from openai import OpenAI\n", |
|
"\n", |
|
"# If you get an error running this cell, then please head over to the troubleshooting notebook!" |
|
] |
|
}, |
|
{ |
|
"cell_type": "markdown", |
|
"id": "6900b2a8-6384-4316-8aaa-5e519fca4254", |
|
"metadata": {}, |
|
"source": [ |
|
"# Connecting to OpenAI" |
|
] |
|
}, |
|
{ |
|
"cell_type": "code", |
|
"execution_count": 2, |
|
"id": "7b87cadb-d513-4303-baee-a37b6f938e4d", |
|
"metadata": {}, |
|
"outputs": [ |
|
{ |
|
"name": "stdout", |
|
"output_type": "stream", |
|
"text": [ |
|
"API key found and looks good so far!\n" |
|
] |
|
} |
|
], |
|
"source": [ |
|
"# Load environment variables in a file called .env\n", |
|
"\n", |
|
"load_dotenv(override=True)\n", |
|
"api_key = os.getenv('OPENAI_API_KEY')\n", |
|
"\n", |
|
"# Check the key\n", |
|
"\n", |
|
"if not api_key:\n", |
|
" print(\"No API key was found - please head over to the troubleshooting notebook in this folder to identify & fix!\")\n", |
|
"elif not api_key.startswith(\"sk-proj-\"):\n", |
|
" print(\"An API key was found, but it doesn't start sk-proj-; please check you're using the right key - see troubleshooting notebook\")\n", |
|
"elif api_key.strip() != api_key:\n", |
|
" print(\"An API key was found, but it looks like it might have space or tab characters at the start or end - please remove them - see troubleshooting notebook\")\n", |
|
"else:\n", |
|
" print(\"API key found and looks good so far!\")\n" |
|
] |
|
}, |
|
{ |
|
"cell_type": "code", |
|
"execution_count": 3, |
|
"id": "019974d9-f3ad-4a8a-b5f9-0a3719aea2d3", |
|
"metadata": {}, |
|
"outputs": [], |
|
"source": [ |
|
"openai = OpenAI()" |
|
] |
|
}, |
|
{ |
|
"cell_type": "code", |
|
"execution_count": 4, |
|
"id": "51d42a08-188e-4c56-9578-47cd549bd1d8", |
|
"metadata": {}, |
|
"outputs": [], |
|
"source": [ |
|
"from urllib.parse import urlencode\n", |
|
"import datetime\n", |
|
"\n", |
|
"headers = {\n", |
|
" \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36\"\n", |
|
"}" |
|
] |
|
}, |
|
{ |
|
"cell_type": "code", |
|
"execution_count": 5, |
|
"id": "682eff74-55c4-4d4b-b267-703edbc293c7", |
|
"metadata": {}, |
|
"outputs": [], |
|
"source": [ |
|
"class YahooFinanceWebsite:\n", |
|
" def __init__(self, stock_symbol):\n", |
|
" \"\"\"\n", |
|
" Create this Website object from the given url using the BeautifulSoup library\n", |
|
" \"\"\"\n", |
|
" self.stock_symbol = stock_symbol.upper()\n", |
|
"\n", |
|
" def __build_url(self, params):\n", |
|
" base_url = f\"https://finance.yahoo.com/quote/{self.stock_symbol}/history/\"\n", |
|
" query_string = urlencode(params)\n", |
|
" return f\"{base_url}?{query_string}\"\n", |
|
"\n", |
|
" def get_stock_data(self):\n", |
|
" datetime_now = datetime.datetime.now()\n", |
|
" datetime_year_ago = datetime_now - datetime.timedelta(days=365)\n", |
|
" params = {\"frequency\": \"1wk\", \"period1\": datetime_year_ago.timestamp(), \"period2\": datetime_now.timestamp()}\n", |
|
" url = self.__build_url(params)\n", |
|
" response = requests.get(url, headers=headers)\n", |
|
"\n", |
|
" soup = BeautifulSoup(response.content, 'html.parser')\n", |
|
" \n", |
|
" title = soup.title.string if soup.title else \"No title found\"\n", |
|
" for irrelevant in soup.body([\"script\", \"style\", \"img\", \"input\"]):\n", |
|
" irrelevant.decompose()\n", |
|
"\n", |
|
" html_table_data = soup.find(\"table\")\n", |
|
"\n", |
|
" return title, html_table_data" |
|
] |
|
}, |
|
{ |
|
"cell_type": "code", |
|
"execution_count": 6, |
|
"id": "70b8d7e7-51e7-4392-9b85-9ac9f67a907c", |
|
"metadata": {}, |
|
"outputs": [], |
|
"source": [ |
|
"def build_stock_analysis_prompt(stock_symbol, title, stock_table_data):\n", |
|
" sys_prompt = r\"\"\"You are an assistant that analyzes the contents of HTML formated table that contains data on a specific stock.\n", |
|
" The HTML table contains the date, open price, close price, low and highs aggregated for every week over one year timeframe.\n", |
|
" Ignoring text, tags or html attributes that might be navigation related. \n", |
|
" Respond in Markdown format\"\"\"\n", |
|
" \n", |
|
" user_prompt = f\"The data provided below in the HTML table format for {stock_symbol} from the Yahoo Finances.\\\n", |
|
" Make the explaination easy enough for a newbie to understand. \\\n", |
|
" Analyze and Summarize the trends on this stock:\\n{stock_table_data}\\n\\n\\\n", |
|
" Also, calculate the total returns in percentage one could have expected over this period.\"\n", |
|
" \n", |
|
" return [\n", |
|
" {\"role\": \"system\", \"content\": sys_prompt},\n", |
|
" {\"role\": \"user\", \"content\": user_prompt}\n", |
|
" ]" |
|
] |
|
}, |
|
{ |
|
"cell_type": "code", |
|
"execution_count": 7, |
|
"id": "de514421-4cc8-4881-85b4-97f03e94c589", |
|
"metadata": {}, |
|
"outputs": [], |
|
"source": [ |
|
"def analyze_stock_trends(stock_symbol):\n", |
|
" stock_data_page = YahooFinanceWebsite(stock_symbol)\n", |
|
" title, stock_table_data = stock_data_page.get_stock_data()\n", |
|
" response = openai.chat.completions.create(\n", |
|
" model = \"gpt-4o-mini\",\n", |
|
" messages = build_stock_analysis_prompt(stock_symbol, title, stock_table_data)\n", |
|
" )\n", |
|
" return response.choices[0].message.content\n", |
|
"\n", |
|
"def display_analysis(stock_symbol):\n", |
|
" display(Markdown(analyze_stock_trends(stock_symbol)))" |
|
] |
|
}, |
|
{ |
|
"cell_type": "code", |
|
"execution_count": 8, |
|
"id": "41acc36f-484a-4257-a240-cf27520e7396", |
|
"metadata": {}, |
|
"outputs": [ |
|
{ |
|
"data": { |
|
"text/markdown": [ |
|
"## Stock Performance Analysis for GOOG\n", |
|
"\n", |
|
"The following is an analysis based on the provided data from the weekly performance of Google (GOOG) stock over a year. Here’s a breakdown of the key trends and observations:\n", |
|
"\n", |
|
"### Key Data Metrics\n", |
|
"\n", |
|
"- **Date Range**: The last recorded week was on March 21, 2025.\n", |
|
"- **Opening Price**: The price at which the stock opened at the start of the period was generally high, around $163.32.\n", |
|
"- **Closing Price**: The closing price also displayed variability with a notable peak reaching as high as $206.25 at some points.\n", |
|
"- **High and Low Prices**: Price variation indicates several peaks and troughs, with highs occasionally exceeding $200, while lows dipped to around $148.\n", |
|
"\n", |
|
"### Summary of Trends\n", |
|
"\n", |
|
"1. **Overall Upward Trend**:\n", |
|
" - Starting from around $150 on March 25, 2024, the stock reached approximately $166 by March 21, 2025. This suggests a gradual increase in the stock price over this period despite fluctuations.\n", |
|
" \n", |
|
"2. **Price Volatility**:\n", |
|
" - The stock experienced several fluctuations where the high price during the week often exceeded $200, signaling periods of strong market interest.\n", |
|
" - The lows reflected corrections; for instance, the lowest weekly closing was around $148, suggesting some weeks where buying pressure was lower.\n", |
|
"\n", |
|
"3. **Volume Trends**:\n", |
|
" - There was a considerable trading volume in many weeks, especially during price fluctuations. The weekly volumes often surpassed tens of millions, showing active trading.\n", |
|
"\n", |
|
"4. **Dividends**:\n", |
|
" - There were multiple dividends noted (e.g., $0.20 per share weeks), reflecting a strategy to share profits with shareholders.\n", |
|
"\n", |
|
"### Returns Calculation\n", |
|
"\n", |
|
"To calculate the total returns based on closing prices:\n", |
|
"\n", |
|
"- **Starting Price (Closing Price on March 25, 2024)**: $152.26\n", |
|
"- **Ending Price (Closing Price on March 21, 2025)**: $166.25\n", |
|
"\n", |
|
"#### Calculation:\n", |
|
"\n", |
|
"\\[\n", |
|
"\\text{Total Return} = \\left(\\frac{\\text{Ending Price} - \\text{Starting Price}}{\\text{Starting Price}}\\right) \\times 100\n", |
|
"\\]\n", |
|
"\n", |
|
"Substituting the values in:\n", |
|
"\n", |
|
"\\[\n", |
|
"\\text{Total Return} = \\left(\\frac{166.25 - 152.26}{152.26}\\right) \\times 100 \\approx \\left(\\frac{13.99}{152.26}\\right) \\times 100 \\approx 9.17\\%\n", |
|
"\\]\n", |
|
"\n", |
|
"### Conclusion\n", |
|
"\n", |
|
"- **Total Returns**: An investor in GOOG could have expected approximately **9.17%** total returns over the analyzed period.\n", |
|
"- The continued interest in Google stock, indicated by consistent trading volumes and dividends, along with the upward trajectory, suggests that it remains a strong candidate for investors looking to hold positions in tech stocks.\n", |
|
"\n", |
|
"This summary reflects the trends and performance of Google's stock based on the provided data, offering insights into trading behaviors and potential investment opportunities." |
|
], |
|
"text/plain": [ |
|
"<IPython.core.display.Markdown object>" |
|
] |
|
}, |
|
"metadata": {}, |
|
"output_type": "display_data" |
|
} |
|
], |
|
"source": [ |
|
"display_analysis(\"GOOG\")" |
|
] |
|
}, |
|
{ |
|
"cell_type": "code", |
|
"execution_count": null, |
|
"id": "7e09541f-bbc4-4cf3-a1ef-9ed5e1b718e4", |
|
"metadata": {}, |
|
"outputs": [], |
|
"source": [ |
|
"display_analysis(\"PFE\")" |
|
] |
|
}, |
|
{ |
|
"cell_type": "code", |
|
"execution_count": null, |
|
"id": "e6af9395-0c5c-4265-a309-baba786bfa71", |
|
"metadata": {}, |
|
"outputs": [], |
|
"source": [ |
|
"display_analysis(\"AAPL\")" |
|
] |
|
}, |
|
{ |
|
"cell_type": "code", |
|
"execution_count": null, |
|
"id": "afe4f6d1-a6ea-44b5-81ae-8e756cfc0d84", |
|
"metadata": {}, |
|
"outputs": [], |
|
"source": [] |
|
} |
|
], |
|
"metadata": { |
|
"kernelspec": { |
|
"display_name": "Python 3 (ipykernel)", |
|
"language": "python", |
|
"name": "python3" |
|
}, |
|
"language_info": { |
|
"codemirror_mode": { |
|
"name": "ipython", |
|
"version": 3 |
|
}, |
|
"file_extension": ".py", |
|
"mimetype": "text/x-python", |
|
"name": "python", |
|
"nbconvert_exporter": "python", |
|
"pygments_lexer": "ipython3", |
|
"version": "3.11.11" |
|
} |
|
}, |
|
"nbformat": 4, |
|
"nbformat_minor": 5 |
|
}
|
|
|