最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于Python制作股票交易計算器

 更新時間:2024年12月19日 10:43:32   作者:PieroPc  
這篇文章主要為大家詳細(xì)介紹了如何利用Python和Html分別制作一個股票交易計算器,文中的示例代碼簡潔易懂,有需要的小伙伴可以參考一下

python版

完整代碼

import tkinter as tk
from tkinter import ttk, messagebox
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from datetime import datetime
 
class StockDesigner:
    def __init__(self, root):
        self.root = root
        self.root.title("股票交易計算器")
        self.root.geometry("1000x700")
        
        # 設(shè)置主題樣式
        style = ttk.Style()
        style.theme_use('clam')  # 使用 clam 主題
        
        # 自定義樣式
        style.configure('TLabel', font=('微軟雅黑', 10))
        style.configure('TButton', font=('微軟雅黑', 10))
        style.configure('TLabelframe', font=('微軟雅黑', 10))
        style.configure('TLabelframe.Label', font=('微軟雅黑', 10, 'bold'))
        style.configure('Custom.TButton', padding=10, font=('微軟雅黑', 10, 'bold'))
        
        # 設(shè)置默認(rèn)手續(xù)費(fèi)率
        self.commission_rate = 0.00025
        self.stamp_duty = 0.001
        self.min_commission = 5
        
        # 創(chuàng)建主框架
        self.main_frame = ttk.Frame(root, padding="20")
        self.main_frame.grid(row=0, column=0, sticky="nsew")
        
        self.create_widgets()
        
        # 配置根窗口的網(wǎng)格權(quán)重
        root.grid_rowconfigure(0, weight=1)
        root.grid_columnconfigure(0, weight=1)
        
    def create_widgets(self):
        # 創(chuàng)建標(biāo)題
        title_label = ttk.Label(self.main_frame, text="股票交易計算器", 
                              font=('微軟雅黑', 16, 'bold'))
        title_label.grid(row=0, column=0, columnspan=2, pady=(0, 20))
        
        # 創(chuàng)建左側(cè)輸入框架
        input_frame = ttk.LabelFrame(self.main_frame, text="交易數(shù)據(jù)輸入", padding="20")
        input_frame.grid(row=1, column=0, padx=(0, 10), sticky="nsew")
        
        # 修改輸入框布局
        labels = ["股票代碼:", "買入價格:", "買入數(shù)量:", "目標(biāo)賣出價:", "目標(biāo)盈利金額:"]
        entries = ["code_entry", "buy_price_entry", "volume_entry", "sell_price_entry", "target_profit_entry"]
        
        for i, (label, entry) in enumerate(zip(labels, entries)):
            ttk.Label(input_frame, text=label).grid(row=i, column=0, pady=10, padx=(0, 10), sticky="e")
            entry_widget = ttk.Entry(input_frame, width=25, font=('微軟雅黑', 10))
            entry_widget.grid(row=i, column=1, pady=10, sticky="w")
            setattr(self, entry, entry_widget)
        
        # 添加說明文本
        hint_text = "注:手續(xù)費(fèi)率為萬分之2.5,印花稅為千分之1"
        ttk.Label(input_frame, text=hint_text, font=('微軟雅黑', 9), foreground='gray')\
            .grid(row=len(labels), column=0, columnspan=2, pady=(10, 0))
        
        # 添加兩個計算按鈕
        calc_button = ttk.Button(input_frame, text="計算交易成本和收益", 
                               command=self.calculate_profit, style='Custom.TButton')
        calc_button.grid(row=len(labels)+1, column=0, columnspan=2, pady=(20,5))
        
        reverse_calc_button = ttk.Button(input_frame, text="計算目標(biāo)賣出價", 
                                       command=self.calculate_target_price, style='Custom.TButton')
        reverse_calc_button.grid(row=len(labels)+2, column=0, columnspan=2, pady=(5,20))
        
        # 創(chuàng)建右側(cè)顯示框架
        display_frame = ttk.LabelFrame(self.main_frame, text="計算結(jié)果", padding="20")
        display_frame.grid(row=1, column=1, sticky="nsew")
        
        # 創(chuàng)建結(jié)果顯示區(qū)
        self.result_text = tk.Text(display_frame, height=20, width=45, 
                                 font=('Consolas', 10), bg='#F8F8F8')
        self.result_text.grid(row=0, column=0, sticky="nsew")
        
        # 添???滾動條
        scrollbar = ttk.Scrollbar(display_frame, orient="vertical", 
                                command=self.result_text.yview)
        scrollbar.grid(row=0, column=1, sticky="ns")
        self.result_text.configure(yscrollcommand=scrollbar.set)
        
        # 設(shè)置網(wǎng)格權(quán)重
        self.main_frame.grid_columnconfigure(1, weight=1)
        self.main_frame.grid_rowconfigure(1, weight=1)
        display_frame.grid_columnconfigure(0, weight=1)
        display_frame.grid_rowconfigure(0, weight=1)
        
    def calculate_profit(self):
        try:
            buy_price = float(self.buy_price_entry.get())
            volume = int(self.volume_entry.get())
            sell_price = float(self.sell_price_entry.get())
            
            if not all([buy_price > 0, volume > 0, sell_price > 0]):
                messagebox.showerror("錯誤", "請輸入有效的數(shù)據(jù)!")
                return
            
            # 計算買入成本
            buy_amount = buy_price * volume
            buy_commission = max(buy_amount * self.commission_rate, self.min_commission)
            
            # 計算賣出收入
            sell_amount = sell_price * volume
            sell_commission = max(sell_amount * self.commission_rate, self.min_commission)
            stamp_duty = sell_amount * self.stamp_duty
            
            # 計算總成本和收益
            total_cost = buy_amount + buy_commission + sell_commission + stamp_duty
            total_income = sell_amount
            net_profit = total_income - total_cost
            profit_rate = (net_profit / total_cost) * 100
            
            # 顯示結(jié)果
            result = f"""┌{'─'*40}┐
│            交易明細(xì)                    │
└{'─'*40}┘
 買入價格: {buy_price:.3f}元
 買入數(shù)量: {volume:,}股
 買入金額: {buy_amount:,.2f}元
 買入手續(xù)費(fèi): {buy_commission:.2f}元
 賣出價格: {sell_price:.3f}元
 賣出金額: {sell_amount:,.2f}元
 賣出手續(xù)費(fèi): {sell_commission:.2f}元
 印花稅: {stamp_duty:.2f}元
┌{'─'*40}┐
│            盈虧分析                    │
└{'─'*40}┘
 總成本: {total_cost:,.2f}元
 總收入: {total_income:,.2f}元
 凈利潤: {net_profit:,.2f}元
 收益率: {profit_rate:.2f}%
┌{'─'*40}┐
│            盈虧平衡點(diǎn)                  │
└{'─'*40}┘
 最低賣出價格: {(total_cost/volume):.3f}元
"""
            self.result_text.delete(1.0, tk.END)
            self.result_text.insert(tk.END, result)
            
        except ValueError:
            messagebox.showerror("錯誤", "請輸入正確的數(shù)值!")
 
    def calculate_target_price(self):
        try:
            buy_price = float(self.buy_price_entry.get())
            volume = int(self.volume_entry.get())
            target_profit = float(self.target_profit_entry.get())
            
            if not all([buy_price > 0, volume > 0, target_profit > 0]):
                messagebox.showerror("錯誤", "請輸入有效的數(shù)據(jù)!")
                return
            
            # 計算買入成本
            buy_amount = buy_price * volume
            buy_commission = max(buy_amount * self.commission_rate, self.min_commission)
            
            # 通過二分法查找目標(biāo)賣出價
            left, right = buy_price, buy_price * 2
            target_price = 0
            
            while left <= right:
                mid = (left + right) / 2
                sell_amount = mid * volume
                sell_commission = max(sell_amount * self.commission_rate, self.min_commission)
                stamp_duty = sell_amount * self.stamp_duty
                
                total_cost = buy_amount + buy_commission + sell_commission + stamp_duty
                net_profit = sell_amount - total_cost
                
                if abs(net_profit - target_profit) < 0.01:
                    target_price = mid
                    break
                elif net_profit < target_profit:
                    left = mid + 0.0001
                else:
                    right = mid - 0.0001
            
            # 計算詳細(xì)成本
            buy_amount = buy_price * volume
            buy_commission = max(buy_amount * self.commission_rate, self.min_commission)
            
            sell_amount = target_price * volume
            sell_commission = max(sell_amount * self.commission_rate, self.min_commission)
            stamp_duty = sell_amount * self.stamp_duty
            
            total_cost = buy_amount + buy_commission + sell_commission + stamp_duty
            
            # 修改顯示結(jié)果,添加成本明細(xì)
            result = f"""┌{'─'*40}┐
│            反向計算結(jié)果                │
└{'─'*40}┘
 買入價格: {buy_price:.3f}元
 買入數(shù)量: {volume:,}股
 買入金額: {buy_amount:,.2f}元
 買入手續(xù)費(fèi): {buy_commission:.2f}元
 目標(biāo)盈利: {target_profit:.2f}元
 需要賣出價格: {target_price:.3f}元
 賣出金額: {sell_amount:,.2f}元
 賣出手續(xù)費(fèi): {sell_commission:.2f}元
 印花稅: {stamp_duty:.2f}元
┌{'─'*40}┐
│            成本與收益                  │
└{'─'*40}┘
 總成本: {total_cost:,.2f}元
 總收入: {sell_amount:,.2f}元
 凈利潤: {target_profit:.2f}元
 上漲幅度: {((target_price/buy_price - 1) * 100):.2f}%
"""
            self.result_text.delete(1.0, tk.END)
            self.result_text.insert(tk.END, result)
            
            # 自動填充賣出價格輸入框
            self.sell_price_entry.delete(0, tk.END)
            self.sell_price_entry.insert(0, f"{target_price:.3f}")
            
        except ValueError:
            messagebox.showerror("錯誤", "請輸入正確的數(shù)值!")
 
if __name__ == "__main__":
    root = tk.Tk()
    app = StockDesigner(root)
    root.mainloop()

效果圖

Html 版

完整代碼

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>股票交易計算器</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
        }
        .calculator {
            border: 1px solid #ccc;
            padding: 20px;
            border-radius: 5px;
        }
        .input-group {
            margin-bottom: 15px;
        }
        label {
            display: inline-block;
            width: 120px;
        }
        input {
            width: 150px;
            padding: 5px;
        }
        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        .result {
            margin-top: 20px;
            padding: 10px;
            background-color: #f9f9f9;
        }
    </style>
</head>
<body>
    <div class="calculator">
        <h2>股票交易計算器</h2>
        <div class="input-group">
            <label>買入價格:</label>
            <input type="number" id="buyPrice" step="0.01">
        </div>
        <div class="input-group">
            <label>賣出價格:</label>
            <input type="number" id="sellPrice" step="0.01">
        </div>
        <div class="input-group">
            <label>交易數(shù)量:</label>
            <input type="number" id="quantity">
        </div>
        <div class="input-group">
            <label>手續(xù)費(fèi)率:</label>
            <input type="number" id="feeRate" value="0.00025" step="0.0001">
        </div>
        <button onclick="calculate()">計算</button>
        <div class="result" id="result"></div>
    </div>
 
    <script>
        function calculate() {
            // 獲取輸入值
            const buyPrice = parseFloat(document.getElementById('buyPrice').value);
            const sellPrice = parseFloat(document.getElementById('sellPrice').value);
            const quantity = parseInt(document.getElementById('quantity').value);
            const feeRate = parseFloat(document.getElementById('feeRate').value);
 
            // 驗(yàn)證輸入
            if (!buyPrice || !sellPrice || !quantity || !feeRate) {
                alert('請?zhí)顚懰斜匾畔ⅲ?);
                return;
            }
 
            // 計算交易費(fèi)用
            const buyTotal = buyPrice * quantity;
            const sellTotal = sellPrice * quantity;
            const buyFee = Math.max(buyTotal * feeRate, 5); // 最低手續(xù)費(fèi)5元
            const sellFee = Math.max(sellTotal * feeRate, 5);
 
            // 計算盈虧
            const profit = sellTotal - buyTotal - buyFee - sellFee;
            const profitRate = (profit / buyTotal * 100).toFixed(2);
 
            // 顯示結(jié)果
            const resultHTML = `
                <h3>交易明細(xì):</h3>
                <p>買入總額:¥${buyTotal.toFixed(2)}</p>
                <p>買入手續(xù)費(fèi):¥${buyFee.toFixed(2)}</p>
                <p>賣出總額:¥${sellTotal.toFixed(2)}</p>
                <p>賣出手續(xù)費(fèi):¥${sellFee.toFixed(2)}</p>
                <p>凈盈虧:¥${profit.toFixed(2)}</p>
                <p>收益率:${profitRate}%</p>
            `;
            
            document.getElementById('result').innerHTML = resultHTML;
        }
    </script>
</body>
</html>

效果圖

到此這篇關(guān)于基于Python制作股票交易計算器的文章就介紹到這了,更多相關(guān)Python股票交易計算器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 詳解如何利用Python代碼刪除Word文檔空白行

    詳解如何利用Python代碼刪除Word文檔空白行

    Word文檔內(nèi)容的整潔性與易讀性是體現(xiàn)文檔水平的關(guān)鍵因素之一,許多錯誤或不合理的內(nèi)容,如多余的空白行,Python為批量刪除Word文檔空白行以及對這一過程的自動化處理提供了強(qiáng)有力的支持,本文將介紹如何利用Python自動化刪除Word文檔中的空白行,需要的朋友可以參考下
    2024-05-05
  • Python格式化字符串f-string概覽(小結(jié))

    Python格式化字符串f-string概覽(小結(jié))

    這篇文章主要介紹了Python格式化字符串f-string概覽(小結(jié)),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-06-06
  • python利用線程生成不同尺寸的縮略圖實(shí)例詳解

    python利用線程生成不同尺寸的縮略圖實(shí)例詳解

    這篇文章主要介紹了python利用線程生成不同尺寸的縮略圖,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-05-05
  • 詳解Python的迭代器、生成器以及相關(guān)的itertools包

    詳解Python的迭代器、生成器以及相關(guān)的itertools包

    這篇文章主要介紹了詳解Python的迭代器、生成器以及相關(guān)的itertools包,Iterators、Generators是Python的高級特性,亦是Python學(xué)習(xí)當(dāng)中必會的基本知識,需要的朋友可以參考下
    2015-04-04
  • Python寫一個簡單的在線編輯器

    Python寫一個簡單的在線編輯器

    這篇文章主要介紹了如何利用Python寫一個簡單的在線編輯器,主要通過pywebio程序,實(shí)現(xiàn)了Python的簡陋在線編輯器,需要的小伙伴可以參考一下,希望對你有所幫助
    2022-02-02
  • python 判斷字符串中是否含有漢字或非漢字的實(shí)例

    python 判斷字符串中是否含有漢字或非漢字的實(shí)例

    今天小編就為大家分享一篇python 判斷字符串中是否含有漢字或非漢字的實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • zip在python中的用法小結(jié)

    zip在python中的用法小結(jié)

    Python中的zip函數(shù)是一個非常有用的工具,可以幫助我們同時處理多個可迭代對象,通過使用zip函數(shù),我們可以將多個列表或迭代器中的元素打包成一個個元組,然后返回由這些元組組成的列表,這篇文章介紹zip在python中的用法,感興趣的朋友一起看看吧
    2024-02-02
  • Python中調(diào)試模塊pdb與ipdb操作的全面指南

    Python中調(diào)試模塊pdb與ipdb操作的全面指南

    調(diào)試是編程過程中不可或缺的重要環(huán)節(jié),Python 提供了多種調(diào)試工具,其中 pdb 和 ipdb 是最常用的兩種,下面就跟隨小編一起學(xué)習(xí)一下二者的具體使用吧
    2025-04-04
  • python-opencv在有噪音的情況下提取圖像的輪廓實(shí)例

    python-opencv在有噪音的情況下提取圖像的輪廓實(shí)例

    下面小編就為大家?guī)硪黄猵ython-opencv在有噪音的情況下提取圖像的輪廓實(shí)例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-08-08
  • Python 實(shí)現(xiàn)還原已撤回的微信消息

    Python 實(shí)現(xiàn)還原已撤回的微信消息

    這篇文章主要介紹了Python 神操作,還原已撤回的微信消息功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-06-06

最新評論

怀化市| 公安县| 安溪县| 茌平县| 特克斯县| 陇南市| 利津县| 中西区| 多伦县| 丰城市| 象州县| 光山县| 渝中区| 密云县| 馆陶县| 遵化市| 湄潭县| 勃利县| 台北市| 隆安县| 林口县| 九寨沟县| 理塘县| 汽车| 北碚区| 高平市| 菏泽市| 钟山县| 明光市| 丹棱县| 顺平县| 聊城市| 高台县| 镇江市| 益阳市| 澎湖县| 公安县| 那坡县| 蒙山县| 天峨县| 柳州市|