005.做個搜尋的功能

更新於 發佈於 閱讀時間約 14 分鐘

Q: 承接之前的程式,做一個搜尋對話框

raw-image


GPT回覆如下:

A:

要實現一個前端的搜尋框來按 stock_id 搜尋並展示結果,可以按照以下步驟完成:


修改項目結構

在現有的前端目錄中添加搜尋功能,使用搜尋框提交 stock_id,通過 API 返回數據並渲染到表格中。

bash
複製程式碼frontend/
├── index.html # 主頁面,包含搜尋框和表格
├── app.js # 更新 JavaScript 文件,處理搜尋邏輯
├── styles.css # 更新樣式文件

步驟 1:修改後端 API

1. 新增支持搜尋的 API

backend/app.py 中,更新 /api/company_financials,支持根據 stock_id 查詢數據。

python
複製程式碼@app.route('/api/company_financials', methods=['GET'])
def get_company_financials():
"""
從資料庫中聯合查詢公司靜態與財務數據,支持 stock_id 搜索
"""
try:
# 獲取查詢參數
stock_id = request.args.get('stock_id')

# 基礎查詢語句
query = """
SELECT
c.stock_id,
c.company_short_name,
c.paid_in_capital,
f.revenue_million,
f.gross_margin_percent,
f.operating_profit_margin_percent,
f.pretax_profit_margin_percent,
f.net_profit_margin_percent
FROM twse_listed_companies c
JOIN financial_reports f ON c.stock_id = f.stock_id
"""

# 如果有 stock_id 查詢參數,添加 WHERE 條件
if stock_id:
query += " WHERE c.stock_id = :stock_id"
df = pd.read_sql(query, engine, params={"stock_id": stock_id})
else:
df = pd.read_sql(query, engine)

# 返回 JSON 結果
return jsonify(df.to_dict(orient='records'))
except Exception as e:
return jsonify({"error": str(e)}), 500

這樣,API 可以支持按 stock_id 搜索,例如:

arduino
複製程式碼http://127.0.0.1:5000/api/company_financials?stock_id=2330

步驟 2:修改前端 HTML

1. 添加搜尋框

frontend/index.html 中,添加搜尋框和表格。

html
複製程式碼<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Company Financial Search</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Company Financials</h1>

<!-- 搜尋框 -->
<div class="search-container">
<input type="text" id="search-input" placeholder="Enter Stock ID" />
<button id="search-button">Search</button>
</div>

<!-- 表格 -->
<table id="financials-table">
<thead>
<tr>
<th>Stock ID</th>
<th>Company Short Name</th>
<th>Paid-in Capital</th>
<th>Revenue (Million)</th>
<th>Gross Margin (%)</th>
<th>Operating Profit Margin (%)</th>
<th>Pretax Profit Margin (%)</th>
<th>Net Profit Margin (%)</th>
</tr>
</thead>
<tbody>
<!-- Data will be inserted here -->
</tbody>
</table>

<script src="app.js"></script>
</body>
</html>

步驟 3:更新 JavaScript

frontend/app.js 中實現搜尋功能,將 API 結果動態插入表格。

javascript
複製程式碼// Function to fetch and render data
function fetchAndRenderData(stockId = null) {
// API URL
let apiUrl = 'http://127.0.0.1:5000/api/company_financials';
if (stockId) {
apiUrl += `?stock_id=${stockId}`;
}

// Fetch data from API
fetch(apiUrl)
.then(response => response.json())
.then(data => {
const tableBody = document.querySelector('#financials-table tbody');
tableBody.innerHTML = ''; // 清空現有的表格數據

// 如果沒有結果
if (data.length === 0) {
const row = document.createElement('tr');
row.innerHTML = `<td colspan="8">No results found</td>`;
tableBody.appendChild(row);
return;
}

// 插入每筆數據
data.forEach(company => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${company.stock_id}</td>
<td>${company.company_short_name}</td>
<td>${company.paid_in_capital || 'N/A'}</td>
<td>${company.revenue_million || 'N/A'}</td>
<td>${company.gross_margin_percent || 'N/A'}</td>
<td>${company.operating_profit_margin_percent || 'N/A'}</td>
<td>${company.pretax_profit_margin_percent || 'N/A'}</td>
<td>${company.net_profit_margin_percent || 'N/A'}</td>
`;
tableBody.appendChild(row);
});
})
.catch(error => console.error('Error fetching data:', error));
}

// Initial load: fetch all data
fetchAndRenderData();

// Search button event listener
document.getElementById('search-button').addEventListener('click', () => {
const stockId = document.getElementById('search-input').value.trim();
fetchAndRenderData(stockId);
});

步驟 4:更新樣式

frontend/styles.css 中為搜尋框添加樣式:

css
複製程式碼body {
font-family: Arial, sans-serif;
margin: 20px;
}

h1 {
text-align: center;
}

.search-container {
text-align: center;
margin-bottom: 20px;
}

#search-input {
padding: 10px;
width: 300px;
font-size: 16px;
}

#search-button {
padding: 10px 20px;
font-size: 16px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}

#search-button:hover {
background-color: #45a049;
}

table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}

table, th, td {
border: 1px solid #ddd;
}

th, td {
padding: 10px;
text-align: left;
}

th {
background-color: #f4f4f4;
}

tr:nth-child(even) {
background-color: #f9f9f9;
}

完成效果

  1. 初始頁面
    • 顯示所有公司和財務數據。
  2. 搜尋功能
    • 在搜尋框輸入 stock_id,例如 2330
    • 點擊「Search」按鈕,表格會更新為該 stock_id 的相關數據。
    • 若無匹配結果,顯示「No results found」。
avatar-img
3會員
28內容數
人生online之資本市場大作戰
留言0
查看全部
avatar-img
發表第一個留言支持創作者!
微嗑多的沙龍 的其他內容
目前為止的程式架構。 我就是幫忙看架構上有沒有錯的慣老闆。
先說這一篇不是要教怎麼解讀,純粹發牢騷。想看解讀的方法可以回到上一頁了。
剛剛看了一下有哪些資訊要加進資料庫,看起來財務報表蠻適合的,這樣可以將兩個表格整理在網頁資訊內。就請GPT解析JSON並且上工寫程式。
白話一點的意思是:「從公開的資料(API),抓下來放在自己的資料庫(PostgresDB),然後再用網頁(Web.app)的方式呈現出來」
起心動念是因為自己有一套投資邏輯(適用小資產等級,約100萬到200萬的投資級距),每季根據財報分析後,得到8-10隻上市櫃股票,每一隻都要進行基本面的事實查核,然後再看基本面的狀況。覺得這一套邏輯如果一直都是python/Excel/web搜尋/手抄紀錄,感覺真的很麻煩啊。
這個002步驟完成了,接下來我想要有個簡單的網頁可以去找到這資料庫裡的靜態資料。
目前為止的程式架構。 我就是幫忙看架構上有沒有錯的慣老闆。
先說這一篇不是要教怎麼解讀,純粹發牢騷。想看解讀的方法可以回到上一頁了。
剛剛看了一下有哪些資訊要加進資料庫,看起來財務報表蠻適合的,這樣可以將兩個表格整理在網頁資訊內。就請GPT解析JSON並且上工寫程式。
白話一點的意思是:「從公開的資料(API),抓下來放在自己的資料庫(PostgresDB),然後再用網頁(Web.app)的方式呈現出來」
起心動念是因為自己有一套投資邏輯(適用小資產等級,約100萬到200萬的投資級距),每季根據財報分析後,得到8-10隻上市櫃股票,每一隻都要進行基本面的事實查核,然後再看基本面的狀況。覺得這一套邏輯如果一直都是python/Excel/web搜尋/手抄紀錄,感覺真的很麻煩啊。
這個002步驟完成了,接下來我想要有個簡單的網頁可以去找到這資料庫裡的靜態資料。
你可能也想看
Google News 追蹤
Thumbnail
在網路速度有限的情況下,依序記錄不斷產生的資訊,能統計使用者在頁面上操作了哪些功能。
Thumbnail
工具功能 (1) 彈性任意查詢檔案,如對來源目錄設定,檔案修改日期 設定,檔名特定字串或副檔名設定後,自動查出明細,並可展開至各階子目錄處理     (2) 依查詢後結果,可產出 LIST ,提供查詢結果之確認,再依此對檔案作複 (3) 可對檔案作移動,複製至別處,刪除處理,使電腦可騰出硬碟空間
Thumbnail
因為最近想嘗試編碼風格,於是就選了一套比較"不嚴格"的輔助工具來摸索。 編輯器 VS CODE 框架 VUE3 打包工具 VITE 編碼風格 Standard 環境 version { "nodejs":"v18.18.0", "npm":"9.8.1" }
Thumbnail
到存放虛擬機的磁碟處\點選想要註冊的機器\註冊機器(登錄虛擬機器)
Thumbnail
這是為了搭建自己想要的工作流而開始的研究工作。
Thumbnail
題目敘述 題目會給我們一組定義好的界面和需求,要求我們設計一個資料結構,可以滿足平均O(1)的插入元素、刪除元素、隨機取得元素的操作。 RandomizedSet() 類別建構子 bool insert(int val) 插入元素的function界面 bool remove(int val
Thumbnail
在網路速度有限的情況下,依序記錄不斷產生的資訊,能統計使用者在頁面上操作了哪些功能。
Thumbnail
工具功能 (1) 彈性任意查詢檔案,如對來源目錄設定,檔案修改日期 設定,檔名特定字串或副檔名設定後,自動查出明細,並可展開至各階子目錄處理     (2) 依查詢後結果,可產出 LIST ,提供查詢結果之確認,再依此對檔案作複 (3) 可對檔案作移動,複製至別處,刪除處理,使電腦可騰出硬碟空間
Thumbnail
因為最近想嘗試編碼風格,於是就選了一套比較"不嚴格"的輔助工具來摸索。 編輯器 VS CODE 框架 VUE3 打包工具 VITE 編碼風格 Standard 環境 version { "nodejs":"v18.18.0", "npm":"9.8.1" }
Thumbnail
到存放虛擬機的磁碟處\點選想要註冊的機器\註冊機器(登錄虛擬機器)
Thumbnail
這是為了搭建自己想要的工作流而開始的研究工作。
Thumbnail
題目敘述 題目會給我們一組定義好的界面和需求,要求我們設計一個資料結構,可以滿足平均O(1)的插入元素、刪除元素、隨機取得元素的操作。 RandomizedSet() 類別建構子 bool insert(int val) 插入元素的function界面 bool remove(int val