使用Python创建一个外汇应用程序

Our Own Score

欢迎阅读第一篇用中文编写的python文章,我一直想用中文创建一个python编程网站,但由于经济困难,我没有这么做。无论如何,虽然我不能创建一个完整的中文网站,但至少我可以创建一个部分的中文python网站与大家分享我的python教程。在将来我们将用python一起创建许多与金融相关的应用程序。在这一章当中,我想与大家分享的第一个例子是下面的外汇应用程序。我们将使用coinbase api创建一个外汇应用程序,它将显示所有世界主要货币的汇率。完整的python程序如下。在下一章中,我将逐步向您解释该程序的用法 。

from coinbase.wallet.client import Client
import json
from tkinter import *
import tkinter.ttk as tk

win = Tk() # Create tk instance
win.title("Real CryptoGeek") # Add a title
win.resizable(0, 0) # Disable resizing the GUI
win.configure(background='white') # change window background color

selectorFrame = Frame(win, background="white") # create top frame to hold search and switch combobox
selectorFrame.pack(anchor = "nw", pady = 2, padx=10)
currency_label = Label(selectorFrame, text = "Select currency pair / base currency :", background="white")
currency_label.pack(anchor="w") # the currency pair label

# Create a combo box for currency pair
select_currency = StringVar() # create a string variable
preferPaired = tk.Combobox(selectorFrame, textvariable=select_currency)
preferPaired.pack(side = LEFT, padx=3)

s = StringVar() # create string variable
# create currency frame and text widget to display the incoming forex data
currencyFrame = Frame(win)
currencyFrame.pack(side=TOP)
currency = Label(currencyFrame)
currency.pack()
text_widget = Text(currency, fg='white', background='black')
text_widget.pack()
s.set("Click the find button to find out the currency exchange rate")
text_widget.insert(END, s.get())

buttonFrame = Frame(win) # create a bottom frame to hold the find button
buttonFrame.pack(side = BOTTOM, fill=X, pady = 6)

def search_currency(): # search currency pair

    countVar = StringVar() # use to hold the character count
    text_widget.tag_remove("search", "1.0", "end") # cleared the hightlighted currency pair

    if(preferPaired.get() != ''):

        pos = text_widget.search(preferPaired.get(), "1.0", stopindex="end", count=countVar)
        text_widget.tag_configure("search", background="green")
        new_pos = float(pos) + float(0.7)
        text_widget.tag_add("search", pos, str(new_pos)) #highlight the background of the searched currency pair
        pos = float(pos) + 2.0
        text_widget.see(str(pos))

action_search = tk.Button(selectorFrame, text="Search", command=search_currency) # button used to search the currency pair within the text widget
action_search.pack(side=LEFT)

# Create base currency combo box
base_currency = StringVar() # create a string variable
based = tk.Combobox(selectorFrame, textvariable=base_currency)
based.pack(side = LEFT, padx=3)

exchange_name_dict = dict() # the dictionary for currency name
base_currency_dict = dict() # the dictionary for base currency

def get_exchange_rate(): # this method will display the incoming forex data after the api called
    # first get the api key and secret from the text file
    f = open("coin.txt", "r")
    api_key = f.readline()
    api_secret = f.readline()
    f.close()

    api_key = api_key.replace('\n', '')
    api_secret = api_secret.replace('\n', '')

    global exchange_rate

    try:
        client = Client(api_key, api_secret)
        market_currencies_o = client.get_exchange_rates()
        market_currencies_s = json.dumps(market_currencies_o)
        exchange_rate = json.loads(market_currencies_s)
        supported_currency = client.get_currencies() # get all the available currencies from coinbase
        exchange_rate_s = json.loads(json.dumps(supported_currency))

    except:
        print("An exception occurred")

    count = 0
    found = False

    curr = tuple() # the tuple which will be populated by currency pairs
    curr1 = tuple() # the tuple which will be populated by base currency
    usd = "USD" # populate the first base currency
    curr1+= (usd,)
    sell_buy = ''

    for key in exchange_rate_s['data']: # populate the exchange_name_dict
        id = key['id']
        name = key['name']
        obj_currency = {id:name}
        exchange_name_dict .update(obj_currency)

    for key in exchange_rate['rates']: # create a dictionary for id and rate

        id = key
        rate = exchange_rate['rates'][key]
        obj_currency = {id: rate}
        base_currency_dict.update(obj_currency)
        curr1 += (id,)

    curr, sell_buy = fill_display_exchange(count, curr, exchange_rate, found, sell_buy)

    # fill up the data for the search currency pair combo box
    preferPaired['values'] = curr
    preferPaired.current(0)  # select item one

    # fill up data for the base currency pair
    based['values'] = curr1
    based.current(0)

    text_widget.delete('1.0', END) # clear all those previous text first
    s.set(sell_buy)
    text_widget.insert(INSERT, s.get()) # display forex rate in text widget

def fill_display_exchange(count, curr, exchange_rate, found, sell_buy): # method used to get the search combo box value and display forex rate

    for key in exchange_rate['rates']:
        count += 1
        c_st = exchange_rate['currency'] + "/" + key
        curr = curr + (c_st,)  # add the search currency pairs
        for e_key in exchange_name_dict:
            if (e_key == key):
                sell_buy += str(count) + ".) Pair : " + exchange_rate['currency'] + "/" + key + " (" + \
                            exchange_name_dict[e_key] + ") : " + \
                            exchange_rate['rates'][key] + '\n'
                found = True
                break
        if (found == False):
            sell_buy += str(count) + ".) Pair : " + exchange_rate['currency'] + "/" + key + " : " + \
                        exchange_rate['rates'][key] + '\n'
        else:
            found = False
    return curr, sell_buy

def switch_currency(): # switch base currency

    sell_buy = ''
    count = 0
    found = False
    the_base_currency = based.get()
    curr = tuple()
    if(the_base_currency != '' and the_base_currency != "USD"):

        for key in exchange_rate['rates']:
            if (the_base_currency != key):
                count += 1
                c_st = the_base_currency + "/" + key
                curr = curr + (c_st,)  # add the currency pairs
                for e_key in exchange_name_dict:
                    if (e_key == key):
                        sell_buy += str(count) + ".) Pair : " + the_base_currency + "/" + key + " (" + \
                            exchange_name_dict[e_key] + ") : " + \
                            str((float(exchange_rate['rates'][key])/float(base_currency_dict[the_base_currency]))) + '\n'
                        found = True
                        break
                if (found == False):
                    sell_buy += str(count) + ".) Pair : " + the_base_currency + "/" + key + " : " + \
                        str((float(exchange_rate['rates'][key]) / float(base_currency_dict[the_base_currency]))) + '\n'
                else:
                    found = False

    elif(the_base_currency != '' and the_base_currency == "USD"):

        curr, sell_buy = fill_display_exchange(count, curr, exchange_rate, found, sell_buy)

    if(the_base_currency != ''):
        # fill up the data for the search currency pair combo box
        preferPaired['values'] = curr
        preferPaired.current(0)  # select item one

        text_widget.delete('1.0', END)  # clear all those previous text first
        s.set(sell_buy)
        text_widget.insert(INSERT, s.get()) # populate the text widget with new forex data

# create the base currency switch button and the find button
action_switch = tk.Button(selectorFrame, text="Switch", command=switch_currency) # button used to switch the base currency
action_switch.pack(side=LEFT)

action_vid = tk.Button(buttonFrame, text="Find", command=get_exchange_rate) # button used to find out the exchange rate of currency pair
action_vid.pack()

win.iconbitmap(r'ico.ico')
win.mainloop()

您如果按下查找按钮,您将看到以下结果。


汇率图表


这是一个关于金融的网站以及关于使用python创建财务应用程序的网站。希望您喜欢。请在本文下面留下您的评论 。

0

Leave a Reply

avatar
  Subscribe  
Notify of