{"id":11950,"date":"2023-05-10T08:40:07","date_gmt":"2023-05-10T15:40:07","guid":{"rendered":"https:\/\/www.pingcap.com\/?p=11950"},"modified":"2024-08-20T06:22:07","modified_gmt":"2024-08-20T13:22:07","slug":"build-with-tidb-cloud-and-streamlit","status":"publish","type":"post","link":"https:\/\/www.pingcap.com\/ko\/blog\/build-with-tidb-cloud-and-streamlit\/","title":{"rendered":"Building an Interactive Web App with TiDB Cloud and Streamlit"},"content":{"rendered":"<p>In today&#8217;s data-driven world, analyzing large datasets quickly and easily is essential. With powerful tools like TiDB Cloud and Streamlit, developers can build custom, interactive user interfaces that make it easier to analyze and visualize data.&nbsp;<\/p>\n\n\n\n<p><a href=\"https:\/\/www.pingcap.com\/ko\/tidb-cloud\/\">TiDB Cloud<\/a> is the fully-managed service of TiDB, an advanced, open-source, distributed SQL database that provides real-time access to transactional data with low latency and horizontal scalability. Combined with Streamlit, TiDB Cloud can provide real-time access to financial data and enable users to analyze and visualize the data in real-time.&nbsp;<\/p>\n\n\n\n<p>Streamlit, on the other hand, is an open-source Python framework that simplifies the process of building web applications. It provides an intuitive API that enables developers to create powerful data applications with minimal effort.&nbsp;<\/p>\n\n\n\n<p>In this post, we&#8217;ll show you how to use TiDB Cloud and Streamlit to build an interactive Stock Data web application. We&#8217;ll walk you through the code to explain some of the building blocks of the application. You\u2019ll learn how to connect to TiDB Cloud, retrieve data from the Yahoo Finance API, and use Plotly to visualize the data. By the end of this tutorial, you&#8217;ll have a better understanding of how to leverage these powerful tools to build similar applications that can streamline your data analysis and visualization workflows.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Prerequisites\"><\/span><strong>Prerequisites<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Before you begin, you will need to set up the following:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A <a href=\"https:\/\/tidbcloud.com\/free-trial\/\">TiDB Cloud account<\/a> and a free Serverless Tier cluster on TiDB Cloud. For details, see <a href=\"https:\/\/docs.pingcap.com\/tidbcloud\/tidb-cloud-quickstart#step-1-create-a-tidb-cluster\">TiDB Cloud Quick Start<\/a>.<\/li>\n\n\n\n<li><a href=\"https:\/\/www.python.org\/downloads\/\">Python 3<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/git-scm.com\/book\/en\/v2\/Getting-Started-Installing-Git\">Git<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Initial_setup\"><\/span><strong>Initial setup&nbsp;<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Setting up the Stock Data Project<\/strong><\/h3>\n\n\n\n<p>1. Clone the integration example <a href=\"https:\/\/github.com\/tidbcloud\/streamlit-stockdata-analysis.git\">code repository<\/a> for TiDB Cloud and Streamlit. From your terminal or command prompt (Windows user), run the following command:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>git clone https:\/\/github.com\/tidbcloud\/streamlit-stockdata-analysis.git <\/code><\/pre>\n\n\n\n<p>2. Navigate to the project&#8217;s root directory &#8220;streamlit-stockdata-analysis&#8221;. Enter:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>cd streamlit-stockdata-analysis<\/code><\/pre>\n\n\n\n<p>3. Install the project dependencies listed in requirements.txt. In the terminal window, enter:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>python3 -m pip install -r requirements.txt<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Storing Database Secrets<\/strong><\/h3>\n\n\n\n<p>We will now create a secrets file to store the <a href=\"https:\/\/docs.pingcap.com\/tidbcloud\/connect-via-standard-connection#serverless-tier\">connection information<\/a> for the TiDB Cloud cluster. The Streamlit app will reference this file to establish a connection with the TiDB database. For more information on connecting a Streamlit app with TiDB, please refer to the Streamlit tutorial, <a href=\"https:\/\/docs.streamlit.io\/knowledge-base\/tutorials\/databases\/tidb\">Connect Streamlit to TiDB<\/a>.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>In the project\u2019s root directory, create a file named .streamlit\/secrets.toml.<\/li>\n\n\n\n<li>Add the following content to the file, replacing the placeholder values with your TiDB Cloud Cluster information:<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>#.streamlit\/secrets.toml\n&#91;tidb]\nhost = \"&lt;TiDB_cluster_host&gt;\"\nport = 4000\ndatabase = \"test\"\nuser = \"&lt;TiDB_cluster_user&gt;\"\npassword = \"&lt;TiDB_cluster_password&gt;\"\nssl_ca = \"&lt;path_to_CA_store&gt;\"<\/code><\/pre>\n\n\n\n<p>The Certificate Authority (CA) store path depends on your operating system. You can find this path in the <strong>Connection<\/strong> tab of the TiDB Cloud cluster. For example, on macOS, the path would be <code>\/etc\/ssl\/cert.pem<\/code>.<\/p>\n\n\n\n<p>For more information on connecting a Streamlit app with TiDB, refer to the <a href=\"https:\/\/docs.streamlit.io\/streamlit-community-cloud\/get-started\/deploy-an-app\/connect-to-data-sources\/secrets-management\">Streamlit documentation<\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Creating a TiDB Table for Storing Stock Data<\/strong><\/h3>\n\n\n\n<p>To store daily historical stock data for a ticker symbol in TiDB, follow these steps:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Log in to the <a href=\"https:\/\/tidbcloud.com\/\">TiDB Console<\/a> and navigate to the cluster overview page.&nbsp;<br><figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"481\" src=\"https:\/\/static.pingcap.com\/files\/2023\/05\/10150108\/image-37-1024x481.png\" alt=\"\" class=\"wp-image-11984\" srcset=\"https:\/\/static.pingcap.com\/files\/2023\/05\/10150108\/image-37-1024x481.png 1024w, https:\/\/static.pingcap.com\/files\/2023\/05\/10150108\/image-37-300x141.png 300w, https:\/\/static.pingcap.com\/files\/2023\/05\/10150108\/image-37-768x361.png 768w, https:\/\/static.pingcap.com\/files\/2023\/05\/10150108\/image-37-1536x722.png 1536w, https:\/\/static.pingcap.com\/files\/2023\/05\/10150108\/image-37-1440x677.png 1440w, https:\/\/static.pingcap.com\/files\/2023\/05\/10150108\/image-37.png 1600w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure><\/li>\n\n\n\n<li>On the left navigation pane, select the <strong>Chat2Query<\/strong> interface, and execute the SQL script shown below. The script creates a `stock_price_history` table inside the test database. This table stores information such as the volume of stock traded, dividends gained, and opening and closing prices.<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>SQL\nCREATE TABLE test.stock_price_history\n(\n  id int PRIMARY KEY AUTO_INCREMENT,\n  Opening_Price DOUBLE,\n  High DOUBLE,\n  Low DOUBLE,\n  Closing_Price DOUBLE,\n  Volume BIGINT,\n  Dividends DOUBLE,\n  Market_Date DATE,\n  Ticker VARCHAR(10)\n);<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>The stock data project in action<\/strong><\/h3>\n\n\n\n<p>Now that you have completed the initial setup, it&#8217;s time to put the project into action.&nbsp; For this walkthrough, we will gather and analyze 10 years of stock historical data for Microsoft (MSFT) and Google (GOOGL). If you\u2019d rather track other stocks, substitute the ticker symbols you\u2019d like. The application retrieves data from the Yahoo Finance API, saves it in TiDB Cloud, and visualizes it using Plotly&#8217;s 3D charts.&nbsp;&nbsp;<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Run the project on your local machine. From the terminal or command prompt (Windows user), enter <code>streamlit run stocks.py<\/code>.<\/li>\n\n\n\n<li>Launch the application in your web browser at http:\/\/localhost:8502.<\/li>\n\n\n\n<li>In the default menu, select <strong>Collect Trade Data<\/strong>. Enter the ticker symbol for the stock you want to analyze, in this case, MSFT.<\/li>\n\n\n\n<li>Leave the start and end dates to their default values, and click <strong>Get Data <\/strong>to retrieve 10 years of historical data for the selected stock.&nbsp;<br><figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"508\" class=\"wp-image-11954\" src=\"https:\/\/static.pingcap.com\/files\/2023\/05\/10024353\/image-32-1024x508.png\" alt=\"\" srcset=\"https:\/\/static.pingcap.com\/files\/2023\/05\/10024353\/image-32-1024x508.png 1024w, https:\/\/static.pingcap.com\/files\/2023\/05\/10024353\/image-32-300x149.png 300w, https:\/\/static.pingcap.com\/files\/2023\/05\/10024353\/image-32-768x381.png 768w, https:\/\/static.pingcap.com\/files\/2023\/05\/10024353\/image-32-1536x762.png 1536w, https:\/\/static.pingcap.com\/files\/2023\/05\/10024353\/image-32-1440x715.png 1440w, https:\/\/static.pingcap.com\/files\/2023\/05\/10024353\/image-32.png 1600w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure><\/li>\n\n\n\n<li>Click <strong>Save Data <\/strong>to store the retrieved stock data in TiDB Cloud.<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"482\" class=\"wp-image-11967\" src=\"https:\/\/static.pingcap.com\/files\/2023\/05\/10080909\/image-35-1024x482.png\" alt=\"\" srcset=\"https:\/\/static.pingcap.com\/files\/2023\/05\/10080909\/image-35-1024x482.png 1024w, https:\/\/static.pingcap.com\/files\/2023\/05\/10080909\/image-35-300x141.png 300w, https:\/\/static.pingcap.com\/files\/2023\/05\/10080909\/image-35-768x361.png 768w, https:\/\/static.pingcap.com\/files\/2023\/05\/10080909\/image-35-1536x723.png 1536w, https:\/\/static.pingcap.com\/files\/2023\/05\/10080909\/image-35-1440x678.png 1440w, https:\/\/static.pingcap.com\/files\/2023\/05\/10080909\/image-35.png 1600w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure><\/li>\n\n\n\n<li>Repeat steps 3-5 to get data for Google, with the ticker symbol GOOGL.<\/li>\n\n\n\n<li>To analyze the data, click <strong>Visualize Trade Data<\/strong>, enter the corresponding ticker symbols, keep the default date values, and click <strong>Visualize<\/strong>.<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"371\" class=\"wp-image-11968\" src=\"https:\/\/static.pingcap.com\/files\/2023\/05\/10080949\/image-36-1024x371.png\" alt=\"\" srcset=\"https:\/\/static.pingcap.com\/files\/2023\/05\/10080949\/image-36-1024x371.png 1024w, https:\/\/static.pingcap.com\/files\/2023\/05\/10080949\/image-36-300x109.png 300w, https:\/\/static.pingcap.com\/files\/2023\/05\/10080949\/image-36-768x278.png 768w, https:\/\/static.pingcap.com\/files\/2023\/05\/10080949\/image-36-1536x557.png 1536w, https:\/\/static.pingcap.com\/files\/2023\/05\/10080949\/image-36-1440x522.png 1440w, https:\/\/static.pingcap.com\/files\/2023\/05\/10080949\/image-36.png 1600w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure><\/li>\n<\/ol>\n\n\n\n<p>This action will execute an analytical query on TiDB and display the results in a 3D chart that compares the total dividend paid and volume traded over the years for Google and Microsoft stocks.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"658\" src=\"https:\/\/static.pingcap.com\/files\/2023\/05\/10031005\/image-33.png\" alt=\"\" class=\"wp-image-11960\" srcset=\"https:\/\/static.pingcap.com\/files\/2023\/05\/10031005\/image-33.png 1024w, https:\/\/static.pingcap.com\/files\/2023\/05\/10031005\/image-33-300x193.png 300w, https:\/\/static.pingcap.com\/files\/2023\/05\/10031005\/image-33-768x494.png 768w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Code_walkthrough\"><\/span><strong>Code walkthrough<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In this section, we&#8217;ll examine important elements of the Stock Data Project&#8217;s code. We\u2019ll explore the application\u2019s components and how they interact to collect, analyze, and visualize historical stock data. We&#8217;ll also discuss the various packages used and how they contribute to the application&#8217;s overall functionality.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Packages used<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import streamlit as st\nimport yfinance as yf\nimport pandas as pd\nimport plotly.express as px\nimport pymysql<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Package<\/strong><\/td><td><strong>Description<\/strong><\/td><\/tr><tr><td><code>streamlit<\/code><\/td><td>Builds web applications for data science and machine learning projects<\/td><\/tr><tr><td><code>yfinance<\/code><\/td><td>Retrieve and analyze historical stock price data from Yahoo Finance<\/td><\/tr><tr><td><code>pandas<\/code><\/td><td>Data manipulation and analysis<\/td><\/tr><tr><td><code>plotly.express<\/code><\/td><td>Creates interactive visualizations<\/td><\/tr><tr><td><code>pymysql<\/code><\/td><td>Interacts with TiDB&nbsp;<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Together, these packages and TiDB provide a powerful toolkit to build interactive web pages that analyze, visualize, and store data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Accessing TiDB&nbsp;<\/strong><\/h3>\n\n\n\n<p>The functions that interact with TiDB provide the foundation for the analysis and visualization capabilities of the project.&nbsp;<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Connecting to the database<\/strong><\/h4>\n\n\n\n<p>The <code>init_connection()<\/code> function connects to the TiDB database using credentials stored in <a href=\"https:\/\/pingcap.feishu.cn\/docx\/GrtodXvzpoGiMex7kGAc5khKnlx#D2k4dKESwogAK2xErXNc5vJqnld\">Streamlit Secrets Manager<\/a>. The function returns a connection object that is used to fetch and store data.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def init_connection():\n    config = st.secrets&#91;\"tidb\"]\n    return pymysql.connect(\n        host=config&#91;\"host\"],\n        port=config&#91;\"port\"],\n        user=config&#91;\"user\"],\n        password=config&#91;\"password\"],\n        database=config&#91;\"database\"],\n        ssl_verify_cert=True,\n        ssl_verify_identity=True,\n        ssl_ca= config&#91;\"ssl_ca\"]\n    ) \n\nconn = init_connection()<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Saving data<\/strong><\/h4>\n\n\n\n<p>The get_ticker_data() function retrieves historical stock data for a given ticker symbol, start date, and end date. Using the <code>yfinance<\/code> library of Yahoo Finance, the function returns a <code>pandas.DataFrame<\/code> that contains the stock&#8217;s open, high, low, close, volume, and dividends:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def get_ticker_data(symbol, start_date, end_date):\n    ticker = yf.Ticker(symbol)\n    data = ticker.history(start=start_date, end=end_date)\n    return data<\/code><\/pre>\n\n\n\n<p>The save_data() function inserts the stock data into the TiDB database using the bulk insert method <code>executemany<\/code> of the <code>pymysql<\/code> library. The function takes a <code>pandas.DataFrame<\/code> and a ticker symbol as input. The function then formats the data and inserts it into the database.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def save_data(data, symbol):\n    data&#91;\"Date\"] = data.index\n    data&#91;\"Ticker\"] = symbol\n    data.reset_index(drop=True, inplace=True)\n\n    df = data.loc&#91;:, &#91;'Open', 'High', 'Low', 'Close', 'Volume', 'Dividends', 'Date', 'Ticker']]\n\n    cur = conn.cursor()\n\n    data = &#91;tuple(row) for row in df.itertuples(index=False)]\n\n    query = 'INSERT INTO stock_price_history (Opening_Price, High, Low, Closing_Price,Volume, Dividends , Market_Date, Ticker) VALUES (  %s,  %s,  %s,  %s, %s,  %s, %s, %s);'\n    cur.executemany(query, data)\n\n    rows_upserted = cur.rowcount\n\n    # commit the changes\n    conn.commit()\n    cur.close()\n    conn.close()\n    st.success( str(rows_upserted) +  \" data saved successfully!\")<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Retrieve data<\/strong><\/h3>\n\n\n\n<p>The <code>fetch_data() <\/code>function leverages TiDB&#8217;s Hybrid Transactional\/Analytical Processing (HTAP) capabilities to execute SQL queries and retrieve aggregated stock data information.&nbsp;&nbsp;<\/p>\n\n\n\n<p>The function accepts two stock ticker symbols and a date range and returns a <code>pandas.DataFrame<\/code> containing the ticker symbols, year, total dividends, and the average volume traded.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def fetch_data(symbol1, symbol2, start_date, end_date):\n    cursor = conn.cursor()\n    query = f\"\"\"\n    SELECT Ticker, YEAR(Market_Date) AS Year, ROUND(SUM(Dividends), 2) AS Total_Dividends, CAST(ROUND(AVG(Volume), 2) AS DOUBLE) AS Avg_Volume\n    FROM stock_price_history\n    WHERE Ticker IN ('{symbol1}', '{symbol2}') AND Market_Date BETWEEN '{start_date}' AND '{end_date}'\n    GROUP BY Ticker, YEAR(Market_Date)\n    ORDER BY Ticker, YEAR(Market_Date) ASC;\n    \"\"\"\n    cursor.execute(query)\n    data = cursor.fetchall()\n    cols = &#91;'Ticker', 'Year', 'Total_Dividends', 'Avg_Volume']\n    df = pd.DataFrame(data, columns=cols)\n    return df<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Web application<\/strong><\/h3>\n\n\n\n<p>The web application lets you collect and visualize historical stock trade data.&nbsp;<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Collecting trade data&nbsp;<\/strong><\/h4>\n\n\n\n<p>The Collect Trade Data page lets users enter a stock ticker symbol, a start date, and an end date. When users click <strong>Get Data<\/strong>, the app retrieves historical trade data for the specified stock within the given date range and displays it in a table. The data is stored in the session state until the user saves it or navigates away from the page.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Define the inputs\nsymbol = st.text_input(\"Ticker Symbol\").upper()\nstart_date = st.date_input(\"Start Date\", value=pd.to_datetime(\"today\").floor(\"D\") - pd.offsets.DateOffset(years=10))\nend_date = st.date_input(\"End Date\", value=pd.to_datetime(\"today\").floor(\"D\"))\n\n# Define the button to retrieve the data\nif st.button(\"Get Data\"):\n    data = get_ticker_data(symbol, start_date, end_date)\n    st.write(data)\n# store data in session\n    st.session_state.data = data<\/code><\/pre>\n\n\n\n<p>Clicking the <strong>Save Data<\/strong> button will add the data to TiDB and clear the session.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Define the button to save the data to TiDB\nif st.button(\"Save Data\"):\n    if st.session_state.get(\"data\") is None:\n        st.write(\"No data to save.\")\n        return\n    data = st.session_state.data\n    save_data(data, symbol)\n    del st.session_state&#91;'data']<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Visualizing trade data&nbsp;<\/strong><\/h4>\n\n\n\n<p>The Visualize Trade Data page lets users enter two stock ticker symbols, a start date, and an end date. When users click <strong>Visualize<\/strong>, the app fetches historical trade data for the specified stocks within the given date range and plots a 3D line chart of the dividend paid versus the volume traded for each stock.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Create two text boxes for entering the stock symbols\nsymbol1 = st.text_input(\"Enter Ticker Symbol\").upper()\nsymbol2 = st.text_input(\"Enter Ticker Symbol to Compare\").upper()\n\n# Create two date pickers for selecting the start and end dates\nstart_date = st.date_input(\"Start Date\", value=pd.to_datetime(\"today\").floor(\"D\") - pd.offsets.DateOffset(years=10))\nend_date = st.date_input(\"End Date\", value=pd.to_datetime(\"today\").floor(\"D\"))\n\nif st.button(\"Visualize\"):\n    # Fetch data from the database\n    data = fetch_data(symbol1, symbol2, start_date, end_date)\n\n    if data.empty:\n        st.warning('No data found for the selected criteria. Please adjust the inputs.')\n    else:\n        # Display the chart\n        plot_3d_line(data)<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Plot 3D Chart<\/strong><\/h4>\n\n\n\n<p>The plot_3d_line function uses the Plotly library to create the 3D line chart. This library offers a variety of interactive visualization tools that can make data more meaningful. By visualizing the relationship between the dividend paid, volume traded, and year for each stock ticker, users can gain insights into the stocks&#8217; performance over time and make more informed investment decisions.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def plot_3d_line(data):\n    fig = px.line_3d(data, x='Year', y='Total_Dividends', z='Avg_Volume', color='Ticker')\n    fig.update_layout(title=f\"Dividend Paid Vs Volume Traded\", height=600, width=800, scene=dict(xaxis_title=\"Year\", yaxis_title=\"Dividends Paid\", zaxis_title=\"Volume Traded\"))\n    st.plotly_chart(fig)<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span><strong>Conclusion<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Building a stock data analysis app using Python and Streamlit can be a powerful tool for visualizing and analyzing financial data. In addition, using TiDB as the backend database can provide horizontal scalability and high availability for the application.&nbsp;<\/p>\n\n\n\n<p>By following the steps outlined in this blog post, you can create an end-to-end trading data analysis app that collects data, saves it to TiDB Cloud, and visualizes it in a way that can provide insights into trading trends and patterns.&nbsp;If you have any questions or feedback, please feel free to contact us through<a href=\"https:\/\/twitter.com\/PingCAP\"> Twitter<\/a>,<a href=\"https:\/\/www.linkedin.com\/company\/pingcap\/mycompany\/\"> LinkedIn<\/a>, or our<a href=\"https:\/\/slack.tidb.io\/invite?team=tidb-community&amp;channel=everyone&amp;ref=pingcap\"> Slack Channel<\/a>.<\/p>\n\n\n\n<p><\/p>","protected":false},"excerpt":{"rendered":"<p>In today&#8217;s data-driven world, analyzing large datasets quickly and easily is essential. With powerful tools like TiDB Cloud and Streamlit, developers can build custom, interactive user interfaces that make it easier to analyze and visualize data.&nbsp; TiDB Cloud is the fully-managed service of TiDB, an advanced, open-source, distributed SQL database that provides real-time access to [&hellip;]<\/p>\n","protected":false},"author":216,"featured_media":11970,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ub_ctt_via":"","footnotes":""},"categories":[13],"tags":[182,10,31],"class_list":["post-11950","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-product","tag-ecosystem","tag-htap","tag-tidb-cloud"],"acf":[],"featured_image_src":"https:\/\/static.pingcap.com\/files\/2023\/05\/10082545\/streamlit_banner.jpg","author_info":{"display_name":"Arun Vijayraghavan","author_link":"https:\/\/www.pingcap.com\/ko\/blog\/author\/arun-vijayraghavan\/"},"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Building an Interactive Web App with TiDB Cloud and Streamlit | TiDB<\/title>\n<meta name=\"description\" content=\"Learn how to build an interactive Stock Data web app using TiDB Cloud and Streamlit. Connect, retrieve, visualize data with ease.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.pingcap.com\/ko\/blog\/build-with-tidb-cloud-and-streamlit\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Building an Interactive Web App with TiDB Cloud and Streamlit | TiDB\" \/>\n<meta property=\"og:description\" content=\"Learn how to build an interactive Stock Data web app using TiDB Cloud and Streamlit. Connect, retrieve, visualize data with ease.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.pingcap.com\/ko\/blog\/build-with-tidb-cloud-and-streamlit\/\" \/>\n<meta property=\"og:site_name\" content=\"TiDB\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/facebook.com\/pingcap2015\" \/>\n<meta property=\"article:published_time\" content=\"2023-05-10T15:40:07+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-08-20T13:22:07+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/static.pingcap.com\/files\/2023\/05\/10083844\/Streamlit_social.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"2000\" \/>\n\t<meta property=\"og:image:height\" content=\"1000\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Arun Vijayraghavan\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:image\" content=\"https:\/\/static.pingcap.com\/files\/2023\/05\/10083844\/Streamlit_social.jpg\" \/>\n<meta name=\"twitter:creator\" content=\"@PingCAP\" \/>\n<meta name=\"twitter:site\" content=\"@PingCAP\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Arun Vijayraghavan\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"10\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/\"},\"author\":{\"name\":\"Arun Vijayraghavan\",\"@id\":\"https:\/\/www.pingcap.com\/#\/schema\/person\/8a9e54493a2a21018fd222e0a32b1ffd\"},\"headline\":\"Building an Interactive Web App with TiDB Cloud and Streamlit\",\"datePublished\":\"2023-05-10T15:40:07+00:00\",\"dateModified\":\"2024-08-20T13:22:07+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/\"},\"wordCount\":1392,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/www.pingcap.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/static.pingcap.com\/files\/2023\/05\/10082545\/streamlit_banner.jpg\",\"keywords\":[\"Ecosystem\",\"HTAP\",\"TiDB Cloud\"],\"articleSection\":[\"Product\"],\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/\",\"url\":\"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/\",\"name\":\"Building an Interactive Web App with TiDB Cloud and Streamlit | TiDB\",\"isPartOf\":{\"@id\":\"https:\/\/www.pingcap.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/static.pingcap.com\/files\/2023\/05\/10082545\/streamlit_banner.jpg\",\"datePublished\":\"2023-05-10T15:40:07+00:00\",\"dateModified\":\"2024-08-20T13:22:07+00:00\",\"description\":\"Learn how to build an interactive Stock Data web app using TiDB Cloud and Streamlit. Connect, retrieve, visualize data with ease.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/#primaryimage\",\"url\":\"https:\/\/static.pingcap.com\/files\/2023\/05\/10082545\/streamlit_banner.jpg\",\"contentUrl\":\"https:\/\/static.pingcap.com\/files\/2023\/05\/10082545\/streamlit_banner.jpg\",\"width\":2000,\"height\":667},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.pingcap.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Building an Interactive Web App with TiDB Cloud and Streamlit\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.pingcap.com\/#website\",\"url\":\"https:\/\/www.pingcap.com\/\",\"name\":\"TiDB\",\"description\":\"TiDB | SQL at Scale\",\"publisher\":{\"@id\":\"https:\/\/www.pingcap.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.pingcap.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"ko-KR\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.pingcap.com\/#organization\",\"name\":\"PingCAP\",\"url\":\"https:\/\/www.pingcap.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/www.pingcap.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/static.pingcap.com\/files\/2021\/11\/pingcap-logo.png\",\"contentUrl\":\"https:\/\/static.pingcap.com\/files\/2021\/11\/pingcap-logo.png\",\"width\":811,\"height\":232,\"caption\":\"PingCAP\"},\"image\":{\"@id\":\"https:\/\/www.pingcap.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/facebook.com\/pingcap2015\",\"https:\/\/x.com\/PingCAP\",\"https:\/\/linkedin.com\/company\/pingcap\",\"https:\/\/youtube.com\/channel\/UCuq4puT32DzHKT5rU1IZpIA\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.pingcap.com\/#\/schema\/person\/8a9e54493a2a21018fd222e0a32b1ffd\",\"name\":\"Arun Vijayraghavan\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/www.pingcap.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/static.pingcap.com\/files\/2022\/10\/17234942\/avatar.jpg\",\"contentUrl\":\"https:\/\/static.pingcap.com\/files\/2022\/10\/17234942\/avatar.jpg\",\"caption\":\"Arun Vijayraghavan\"},\"description\":\"TiDB Cloud Product Manager\",\"url\":\"https:\/\/www.pingcap.com\/ko\/blog\/author\/arun-vijayraghavan\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Building an Interactive Web App with TiDB Cloud and Streamlit | TiDB","description":"Learn how to build an interactive Stock Data web app using TiDB Cloud and Streamlit. Connect, retrieve, visualize data with ease.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.pingcap.com\/ko\/blog\/build-with-tidb-cloud-and-streamlit\/","og_locale":"ko_KR","og_type":"article","og_title":"Building an Interactive Web App with TiDB Cloud and Streamlit | TiDB","og_description":"Learn how to build an interactive Stock Data web app using TiDB Cloud and Streamlit. Connect, retrieve, visualize data with ease.","og_url":"https:\/\/www.pingcap.com\/ko\/blog\/build-with-tidb-cloud-and-streamlit\/","og_site_name":"TiDB","article_publisher":"https:\/\/facebook.com\/pingcap2015","article_published_time":"2023-05-10T15:40:07+00:00","article_modified_time":"2024-08-20T13:22:07+00:00","og_image":[{"width":2000,"height":1000,"url":"https:\/\/static.pingcap.com\/files\/2023\/05\/10083844\/Streamlit_social.jpg","type":"image\/jpeg"}],"author":"Arun Vijayraghavan","twitter_card":"summary_large_image","twitter_image":"https:\/\/static.pingcap.com\/files\/2023\/05\/10083844\/Streamlit_social.jpg","twitter_creator":"@PingCAP","twitter_site":"@PingCAP","twitter_misc":{"Written by":"Arun Vijayraghavan","Est. reading time":"10\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/#article","isPartOf":{"@id":"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/"},"author":{"name":"Arun Vijayraghavan","@id":"https:\/\/www.pingcap.com\/#\/schema\/person\/8a9e54493a2a21018fd222e0a32b1ffd"},"headline":"Building an Interactive Web App with TiDB Cloud and Streamlit","datePublished":"2023-05-10T15:40:07+00:00","dateModified":"2024-08-20T13:22:07+00:00","mainEntityOfPage":{"@id":"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/"},"wordCount":1392,"commentCount":0,"publisher":{"@id":"https:\/\/www.pingcap.com\/#organization"},"image":{"@id":"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/#primaryimage"},"thumbnailUrl":"https:\/\/static.pingcap.com\/files\/2023\/05\/10082545\/streamlit_banner.jpg","keywords":["Ecosystem","HTAP","TiDB Cloud"],"articleSection":["Product"],"inLanguage":"ko-KR","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/","url":"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/","name":"Building an Interactive Web App with TiDB Cloud and Streamlit | TiDB","isPartOf":{"@id":"https:\/\/www.pingcap.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/#primaryimage"},"image":{"@id":"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/#primaryimage"},"thumbnailUrl":"https:\/\/static.pingcap.com\/files\/2023\/05\/10082545\/streamlit_banner.jpg","datePublished":"2023-05-10T15:40:07+00:00","dateModified":"2024-08-20T13:22:07+00:00","description":"Learn how to build an interactive Stock Data web app using TiDB Cloud and Streamlit. Connect, retrieve, visualize data with ease.","breadcrumb":{"@id":"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/"]}]},{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/#primaryimage","url":"https:\/\/static.pingcap.com\/files\/2023\/05\/10082545\/streamlit_banner.jpg","contentUrl":"https:\/\/static.pingcap.com\/files\/2023\/05\/10082545\/streamlit_banner.jpg","width":2000,"height":667},{"@type":"BreadcrumbList","@id":"https:\/\/www.pingcap.com\/blog\/build-with-tidb-cloud-and-streamlit\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.pingcap.com\/"},{"@type":"ListItem","position":2,"name":"Building an Interactive Web App with TiDB Cloud and Streamlit"}]},{"@type":"WebSite","@id":"https:\/\/www.pingcap.com\/#website","url":"https:\/\/www.pingcap.com\/","name":"\ud2f0DB","description":"TiDB | SQL at Scale","publisher":{"@id":"https:\/\/www.pingcap.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.pingcap.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"ko-KR"},{"@type":"Organization","@id":"https:\/\/www.pingcap.com\/#organization","name":"PingCAP","url":"https:\/\/www.pingcap.com\/","logo":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/www.pingcap.com\/#\/schema\/logo\/image\/","url":"https:\/\/static.pingcap.com\/files\/2021\/11\/pingcap-logo.png","contentUrl":"https:\/\/static.pingcap.com\/files\/2021\/11\/pingcap-logo.png","width":811,"height":232,"caption":"PingCAP"},"image":{"@id":"https:\/\/www.pingcap.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/facebook.com\/pingcap2015","https:\/\/x.com\/PingCAP","https:\/\/linkedin.com\/company\/pingcap","https:\/\/youtube.com\/channel\/UCuq4puT32DzHKT5rU1IZpIA"]},{"@type":"Person","@id":"https:\/\/www.pingcap.com\/#\/schema\/person\/8a9e54493a2a21018fd222e0a32b1ffd","name":"Arun Vijayraghavan","image":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/www.pingcap.com\/#\/schema\/person\/image\/","url":"https:\/\/static.pingcap.com\/files\/2022\/10\/17234942\/avatar.jpg","contentUrl":"https:\/\/static.pingcap.com\/files\/2022\/10\/17234942\/avatar.jpg","caption":"Arun Vijayraghavan"},"description":"TiDB Cloud Product Manager","url":"https:\/\/www.pingcap.com\/ko\/blog\/author\/arun-vijayraghavan\/"}]}},"grav_blocks":false,"card_markup":"<a class=\"card-resource bg-white\" href=\"https:\/\/www.pingcap.com\/ko\/blog\/build-with-tidb-cloud-and-streamlit\/\"><div class=\"card-resource__image-container\"><img class=\"card-resource__image\" alt=\"streamlit_banner\" src=\"https:\/\/static.pingcap.com\/files\/2023\/05\/10082545\/streamlit_banner.jpg\" loading=\"lazy\" width=2000 height=667 \/><\/div><div class=\"card-resource__content-container\"><div class=\"card-resource__content-head\"><div class=\"card-resource__category\">Product<\/div><\/div><h5 class=\"card-resource__title\">Building an Interactive Web App with TiDB Cloud and Streamlit<\/h5><\/div><\/a>","_links":{"self":[{"href":"https:\/\/www.pingcap.com\/ko\/wp-json\/wp\/v2\/posts\/11950","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pingcap.com\/ko\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.pingcap.com\/ko\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.pingcap.com\/ko\/wp-json\/wp\/v2\/users\/216"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pingcap.com\/ko\/wp-json\/wp\/v2\/comments?post=11950"}],"version-history":[{"count":28,"href":"https:\/\/www.pingcap.com\/ko\/wp-json\/wp\/v2\/posts\/11950\/revisions"}],"predecessor-version":[{"id":18938,"href":"https:\/\/www.pingcap.com\/ko\/wp-json\/wp\/v2\/posts\/11950\/revisions\/18938"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.pingcap.com\/ko\/wp-json\/wp\/v2\/media\/11970"}],"wp:attachment":[{"href":"https:\/\/www.pingcap.com\/ko\/wp-json\/wp\/v2\/media?parent=11950"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.pingcap.com\/ko\/wp-json\/wp\/v2\/categories?post=11950"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.pingcap.com\/ko\/wp-json\/wp\/v2\/tags?post=11950"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}