在当今的金融市场中,股票交易是一项复杂且需要精确计算的活动。为了帮助投资者更好地管理他们的交易成本和收益,本文介绍了一个使用Python和Tkinter库开发的股票交易计算器。通过这个计算器,用户可以轻松输入股票交易的相关数据,获得准确的交易成本、收益、利润率以及目标卖出价等关键信息。本文将详细解读该计算器的开发过程和功能特点。
python版
完整代码
importtkinterastkfromtkinterimportttk,messageboximportmatplotlib.pyplotaspltfrommatplotlib.backends.backend_tkaggimportFigureCanvasTkAggfromdatetimeimportdatetimeclassStockDesigner:def__init__(self,root):self.root=rootself.root.title(\"股票交易计算器\")self.root.geometry(\"1000x700\")#设置主题样式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\'))#设置默认手续费率self.commission_rate=0.00025self.stamp_duty=0.001self.min_commission=5#创建主框架self.main_frame=ttk.Frame(root,padding=\"20\")self.main_frame.grid(row=0,column=0,sticky=\"nsew\")self.create_widgets()#配置根窗口的网格权重root.grid_rowconfigure(0,weight=1)root.grid_columnconfigure(0,weight=1)defcreate_widgets(self):#创建标题title_label=ttk.Label(self.main_frame,text=\"股票交易计算器\",font=(\'微软雅黑\',16,\'bold\'))title_label.grid(row=0,column=0,columnspan=2,pady=(0,20))#创建左侧输入框架input_frame=ttk.LabelFrame(self.main_frame,text=\"交易数据输入\",padding=\"20\")input_frame.grid(row=1,column=0,padx=(0,10),sticky=\"nsew\")#修改输入框布局labels=[\"股票代码:\",\"买入价格:\",\"买入数量:\",\"目标卖出价:\",\"目标盈利金额:\"]entries=[\"code_entry\",\"buy_price_entry\",\"volume_entry\",\"sell_price_entry\",\"target_profit_entry\"]fori,(label,entry)inenumerate(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=\"注:手续费率为万分之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=\"计算目标卖出价\",command=self.calculate_target_price,style=\'Custom.TButton\')reverse_calc_button.grid(row=len(labels)+2,column=0,columnspan=2,pady=(5,20))#创建右侧显示框架display_frame=ttk.LabelFrame(self.main_frame,text=\"计算结果\",padding=\"20\")display_frame.grid(row=1,column=1,sticky=\"nsew\")#创建结果显示区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)#设置网格权重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)defcalculate_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())ifnotall([buy_price>0,volume>0,sell_price>0]):messagebox.showerror(\"错误\",\"请输入有效的数据!\")return#计算买入成本buy_amount=buy_price*volumebuy_commission=max(buy_amount*self.commission_rate,self.min_commission)#计算卖出收入sell_amount=sell_price*volumesell_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_dutytotal_income=sell_amountnet_profit=total_income-total_costprofit_rate=(net_profit/total_cost)*100#显示结果result=f\"\"\"┌{\'─\'*40}┐│交易明细│└{\'─\'*40}┘买入价格:{buy_price:.3f}元买入数量:{volume:,}股买入金额:{buy_amount:,.2f}元买入手续费:{buy_commission:.2f}元卖出价格:{sell_price:.3f}元卖出金额:{sell_amount:,.2f}元卖出手续费:{sell_commission:.2f}元印花税:{stamp_duty:.2f}元┌{\'─\'*40}┐│盈亏分析│└{\'─\'*40}┘总成本:{total_cost:,.2f}元总收入:{total_income:,.2f}元净利润:{net_profit:,.2f}元收益率:{profit_rate:.2f}%┌{\'─\'*40}┐│盈亏平衡点│└{\'─\'*40}┘最低卖出价格:{(total_cost/volume):.3f}元\"\"\"self.result_text.delete(1.0,tk.END)self.result_text.insert(tk.END,result)exceptValueError:messagebox.showerror(\"错误\",\"请输入正确的数值!\")defcalculate_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())ifnotall([buy_price>0,volume>0,target_profit>0]):messagebox.showerror(\"错误\",\"请输入有效的数据!\")return#计算买入成本buy_amount=buy_price*volumebuy_commission=max(buy_amount*self.commission_rate,self.min_commission)#通过二分法查找目标卖出价left,right=buy_price,buy_price*2target_price=0whileleft<=right:mid=(left+right)/2sell_amount=mid*volumesell_commission=max(sell_amount*self.commission_rate,self.min_commission)stamp_duty=sell_amount*self.stamp_dutytotal_cost=buy_amount+buy_commission+sell_commission+stamp_dutynet_profit=sell_amount-total_costifabs(net_profit-target_profit)<0.01:target_price=midbreakelifnet_profit<target_profit:left=mid+0.0001else:right=mid-0.0001#计算详细成本buy_amount=buy_price*volumebuy_commission=max(buy_amount*self.commission_rate,self.min_commission)sell_amount=target_price*volumesell_commission=max(sell_amount*self.commission_rate,self.min_commission)stamp_duty=sell_amount*self.stamp_dutytotal_cost=buy_amount+buy_commission+sell_commission+stamp_duty#修改显示结果,添加成本明细result=f\"\"\"┌{\'─\'*40}┐│反向计算结果│└{\'─\'*40}┘买入价格:{buy_price:.3f}元买入数量:{volume:,}股买入金额:{buy_amount:,.2f}元买入手续费:{buy_commission:.2f}元目标盈利:{target_profit:.2f}元需要卖出价格:{target_price:.3f}元卖出金额:{sell_amount:,.2f}元卖出手续费:{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}\")exceptValueError:messagebox.showerror(\"错误\",\"请输入正确的数值!\")if__name__==\"__main__\":root=tk.Tk()app=StockDesigner(root)root.mainloop()
效果图
Html 版
完整代码
股票交易计算器 body{font-family:Arial,sans-serif;max-width:600px;margin:0auto;padding:20px;}.calculator{border:1pxsolid#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:10px20px;border:none;border-radius:4px;cursor:pointer;}button:hover{background-color:#45a049;}.result{margin-top:20px;padding:10px;background-color:#f9f9f9;}股票交易计算器