Skip to content

Instantly share code, notes, and snippets.

@shibanovp
Last active May 5, 2023 10:31
Show Gist options
  • Save shibanovp/b5fbda59646d84d25eef8b3a0f97e7dc to your computer and use it in GitHub Desktop.
Save shibanovp/b5fbda59646d84d25eef8b3a0f97e7dc to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"MIT License\n",
"\n",
"Copyright (c) 2023 Pavel Shibanov https://blog.experienced.dev/earnings-report-insights-programmer-decodes-coca-colas-q1-2023-10-q-form/\n",
"\n",
"Permission is hereby granted, free of charge, to any person obtaining a copy\n",
"of this software and associated documentation files (the \"Software\"), to deal\n",
"in the Software without restriction, including without limitation the rights\n",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n",
"copies of the Software, and to permit persons to whom the Software is\n",
"furnished to do so, subject to the following conditions:\n",
"\n",
"The above copyright notice and this permission notice shall be included in all\n",
"copies or substantial portions of the Software.\n",
"\n",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n",
"SOFTWARE."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%pip install httpx beautifulsoup4 langchain openai tiktoken chromadb unstructured pandas gradio python-dotenv"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from dotenv import load_dotenv\n",
"\n",
"load_dotenv()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import httpx\n",
"import pandas as pd\n",
"import json\n",
"import os\n",
"\n",
"\n",
"def get_company_facts(email, cik):\n",
" facts = httpx.get(\n",
" f\"https://data.sec.gov/api/xbrl/companyfacts/CIK{str(cik).zfill(10)}.json\",\n",
" headers={\"User-Agent\": f\"{email}\"},\n",
" )\n",
" return facts.json()\n",
"\n",
"\n",
"def get_fact(facts, field):\n",
" fact = facts[\"facts\"][\"us-gaap\"][field]\n",
" label = fact[\"label\"]\n",
" description = fact[\"description\"]\n",
" fact_history = pd.DataFrame.from_dict(fact[\"units\"][\"USD\"])\n",
" fact_history[\"end\"] = pd.to_datetime(fact_history[\"end\"])\n",
" fact_history[\"val_millions\"] = fact_history[\"val\"] / 1000000\n",
" return fact_history, label, description\n",
"\n",
"\n",
"def get_raw_form(email, cik, accession_number):\n",
" res = httpx.get(\n",
" f\"https://www.sec.gov/Archives/edgar/data/{cik}/{accession_number}.txt\",\n",
" headers={\"User-Agent\": f\"{email}\"},\n",
" )\n",
" return res.text\n",
"\n",
"\n",
"# email = os.getenv('EMAIL', 'your email')\n",
"# facts = get_company_facts(email, '21344')\n",
"# fact, *_ = get_fact(facts, 'Revenues')\n",
"# raw_form = get_raw_form(email, '21344', '0000021344-23-000024')\n",
"# print(raw_form[:1300])\n",
"# fact.head()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from bs4 import BeautifulSoup\n",
"\n",
"\n",
"def get_mdna_html(form_xml):\n",
" xml = BeautifulSoup(form_xml, \"xml\")\n",
" document_10q = None\n",
" for document in xml.find_all(\"DOCUMENT\"):\n",
" document_type = document.find(\"TYPE\")\n",
" if document_type and \"10-Q\" in document_type.get_text():\n",
" document_10q = document\n",
" break\n",
" xbrl = document_10q.find(\"XBRL\")\n",
" body = BeautifulSoup(str(xbrl.find(\"body\")), \"html.parser\")\n",
" item2 = body.find(\n",
" string=\"Item 2. Management’s Discussion and Analysis of Financial Condition and Results of Operations\"\n",
" )\n",
" item3 = body.find(\n",
" string=\"Item 3. Quantitative and Qualitative Disclosures About Market Risk\"\n",
" )\n",
" result = []\n",
" mdna = BeautifulSoup(\"\", \"html.parser\")\n",
" current = item2.parent.find_next()\n",
" while current != item3.parent:\n",
" result.append(current)\n",
" current = current.find_next()\n",
"\n",
" for node in result:\n",
" mdna.append(node)\n",
" return str(mdna)\n",
"\n",
"\n",
"# mdna_html = get_mdna_html(raw_form)\n",
"# mdna_html"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import tempfile\n",
"from langchain.document_loaders import UnstructuredHTMLLoader\n",
"\n",
"\n",
"def get_documents(html):\n",
" with tempfile.NamedTemporaryFile(suffix=\".html\") as mdna:\n",
" with open(mdna.name, \"w\") as file:\n",
" file.write(html)\n",
" loader = UnstructuredHTMLLoader(mdna.name)\n",
" data = loader.load()\n",
" return data\n",
"\n",
"\n",
"# documents = get_documents(mdna_html)\n",
"# documents"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from functools import cache\n",
"from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
"import tiktoken\n",
"\n",
"\n",
"@cache\n",
"def tiktoken_len_builder(model_name):\n",
" tokenizer = tiktoken.encoding_for_model(model_name)\n",
"\n",
" def token_len(text):\n",
" tokens = tokenizer.encode(text, disallowed_special=())\n",
" return len(tokens)\n",
"\n",
" return token_len\n",
"\n",
"\n",
"def split_documents(docs, length_function):\n",
" text_splitter = RecursiveCharacterTextSplitter(\n",
" chunk_size=400,\n",
" chunk_overlap=20,\n",
" length_function=length_function,\n",
" )\n",
" return text_splitter.split_documents(docs)\n",
"\n",
"\n",
"# tiktoken_len = tiktoken_len_builder('text-davinci-003')\n",
"# docs = split_documents(documents, tiktoken_len)\n",
"# total_tokens = sum(tiktoken_len(d.page_content) for d in docs)\n",
"# docs"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from langchain.chains.summarize import load_summarize_chain\n",
"\n",
"\n",
"def summarize_docs(docs, openai_api_key=None):\n",
" llm = OpenAI(temperature=0, openai_api_key=openai_api_key)\n",
" chain = load_summarize_chain(llm, chain_type=\"map_reduce\")\n",
" return chain.run(docs)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from langchain.llms import OpenAI\n",
"from langchain.vectorstores import Chroma\n",
"from langchain.embeddings.openai import OpenAIEmbeddings\n",
"from langchain.chains.question_answering import load_qa_chain\n",
"\n",
"\n",
"class MdnaQA:\n",
" def __init__(self, docs, openai_api_key=None):\n",
" self.docs = docs\n",
" llm = OpenAI(temperature=0, openai_api_key=openai_api_key)\n",
" self.chain = load_qa_chain(llm, chain_type=\"stuff\")\n",
" embeddings = OpenAIEmbeddings()\n",
" self.docsearch = Chroma.from_documents(docs, embeddings)\n",
"\n",
" def ask(self, question):\n",
" input_documents = self.docsearch.similarity_search(question)\n",
" return self.chain.run(input_documents=input_documents, question=question)\n",
"\n",
"\n",
"# q = MdnaQA(docs)\n",
"# q.ask(\"What are the risks?\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try:\n",
" import google.colab\n",
"\n",
" IN_COLAB = True\n",
"except:\n",
" IN_COLAB = False"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import gradio as gr\n",
"\n",
"title = \"Coca Cola's Q1 2023 10-Q\"\n",
"\n",
"fields = {\n",
" \"Cash\": \"CashAndCashEquivalentsAtCarryingValue\",\n",
" \"Liabilities\": \"LiabilitiesCurrent\",\n",
" \"Total Equity\": \"StockholdersEquityIncludingPortionAttributableToNoncontrollingInterest\",\n",
" \"Revenues\": \"Revenues\",\n",
" \"Gross Profit\": \"GrossProfit\",\n",
" \"Net Income (Loss)\": \"NetIncomeLoss\",\n",
" \"Cash by Operations\": \"NetCashProvidedByUsedInOperatingActivities\",\n",
" \"Cash by Investing\": \"NetCashProvidedByUsedInInvestingActivities\",\n",
" \"Cash by Financing\": \"NetCashProvidedByUsedInFinancingActivities\",\n",
" \"Net Cash Increase (Decrease)\": \"CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalentsPeriodIncreaseDecreaseIncludingExchangeRateEffect\",\n",
"}\n",
"\n",
"with gr.Blocks(title=title) as demo:\n",
" gr.Markdown(f\"# {title}\")\n",
" email = gr.Textbox(\n",
" value=os.getenv(\"EMAIL\"),\n",
" type=os.getenv(\"GRADIO_EMAIL_TYPE\", \"email\"),\n",
" label=\"Email to access EDGAR API\",\n",
" )\n",
" cik = gr.Textbox(value=\"21344\", interactive=True, label=\"CIK number\")\n",
" fetch = gr.Button(\"Fetch facts\")\n",
" is_fetched = gr.Textbox(visible=False)\n",
" with gr.Tabs(visible=False) as tabs:\n",
" facts = gr.State()\n",
" for label, field in fields.items():\n",
" with gr.TabItem(label):\n",
" field_var = gr.Variable(field)\n",
" plot = gr.LinePlot().style(container=False)\n",
"\n",
" def update_plot(facts, field):\n",
" fact, label, description = get_fact(facts, field)\n",
" return gr.LinePlot.update(\n",
" fact,\n",
" x=\"end\",\n",
" y=\"val_millions\",\n",
" caption=description,\n",
" tooltip=[\"end\", \"val_millions\"],\n",
" width=512,\n",
" )\n",
"\n",
" is_fetched.change(update_plot, [facts, field_var], outputs=plot)\n",
" with gr.TabItem(\"MD&A\"):\n",
" accession_number = gr.Textbox(\n",
" value=\"0000021344-23-000024\", interactive=True, label=\"Accession number\"\n",
" )\n",
" fetch_mdna_btn = gr.Button(\"Fetch MD&A\")\n",
" with gr.Column(visible=False) as col:\n",
" tokens_total = gr.Textbox(visible=False, label=\"Total tokens\")\n",
" mdna = gr.State([])\n",
"\n",
" def fetch_mdna(email, cik, accession_number):\n",
" raw_form = get_raw_form(email, cik, accession_number)\n",
" mdna_html = get_mdna_html(raw_form)\n",
" documents = get_documents(mdna_html)\n",
" model_name = \"text-davinci-003\"\n",
" tiktoken_len = tiktoken_len_builder(model_name)\n",
" docs = split_documents(documents, tiktoken_len)\n",
" tokens_sum = sum(tiktoken_len(d.page_content) for d in docs)\n",
" _col = gr.Column.update(visible=True)\n",
" _tokens_total = gr.Textbox.update(\n",
" value=str(tokens_sum), visible=True\n",
" )\n",
" return _col, _tokens_total, docs\n",
"\n",
" fetch_mdna_btn.click(\n",
" fetch_mdna,\n",
" [email, cik, accession_number],\n",
" [col, tokens_total, mdna],\n",
" )\n",
" openai_api_key = gr.Text(\n",
" value=os.getenv(\"OPENAI_API_KEY\"),\n",
" type=\"password\",\n",
" label=\"OpenAI api key\",\n",
" )\n",
" summarize = gr.Button(\"Summarize MD&A\")\n",
" summary = gr.TextArea(visible=False)\n",
"\n",
" def summarize_mdna(docs, openai_api_key):\n",
" mdna_summary = summarize_docs(docs, openai_api_key)\n",
" return gr.TextArea.update(mdna_summary, visible=True)\n",
"\n",
" summarize.click(summarize_mdna, [mdna, openai_api_key], [summary])\n",
"\n",
" start_qa = gr.Button(\"Start QA with MD&A\")\n",
" chatbot = gr.Chatbot(label=\"QA with MD&A\", visible=False)\n",
" question = gr.Textbox(\n",
" label=\"Your question\", interactive=True, visible=False\n",
" )\n",
" qa_chat = gr.State()\n",
"\n",
" def start_chat(docs, openai_api_key):\n",
" qa_chat = MdnaQA(docs, openai_api_key)\n",
" return (\n",
" qa_chat,\n",
" gr.Textbox.update(visible=True),\n",
" gr.Textbox.update(visible=True),\n",
" )\n",
"\n",
" start_qa.click(\n",
" start_chat, [mdna, openai_api_key], [qa_chat, chatbot, question]\n",
" )\n",
"\n",
" def respond(qa_chat, question, chat_history):\n",
" answer = qa_chat.ask(question)\n",
" chat_history.append((question, answer))\n",
" return \"\", chat_history\n",
"\n",
" question.submit(\n",
" respond, [qa_chat, question, chatbot], [question, chatbot]\n",
" )\n",
"\n",
" def fetch_facts(email, cik):\n",
" t = gr.Tabs.update()\n",
" facts = get_company_facts(email, cik)\n",
" visible = True\n",
" t[\"visible\"] = visible\n",
" return t, visible, facts\n",
"\n",
" fetch.click(fetch_facts, [email, cik], [tabs, is_fetched, facts], queue=False)\n",
"\n",
"demo.launch(share=IN_COLAB, debug=True)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "langchain-tutorial",
"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.10.10"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment