Wednesday, March 27, 2019

leftmouseclickin: Plot triple exponential moving average time series graph with python

Our Own Score

Welcome back again to the ongoing Stock and Forex project, before we start I just want to let you all know that pycharm 2019 is ready for download, I am using pycharm for this project and today mine pycharm editor has just get updated to the pycharm 2019 version which has lots of new features in it. OK so much for that, let get started. In this chapter, we are going to plot the triple exponential moving average time serie graph. As usual, we have created a new method and a button for that method. Below is the revised version of the project.

triple exponential moving average time series
import json
from tkinter import *
import tkinter.ttk as tk
from alpha_vantage.foreignexchange import ForeignExchange
from alpha_vantage.techindicators import TechIndicators
from alpha_vantage.timeseries import TimeSeries
import matplotlib.pyplot as plt
from alpha_vantage.sectorperformance import SectorPerformances

win = Tk() # Create tk instance
win.title("Real Forex n Stock") # 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 the top frame to hold base and quote currency combobox
selectorFrame.pack(anchor = "nw", pady = 2, padx=10)
currency_label = Label(selectorFrame, text = "Select base currency / quote currency :", background="white")
currency_label.pack(anchor="w") # the currency pair label

selector1Frame = Frame(win, background="white") # create the middle frame to hold base and quote currency combobox
selector1Frame.pack(anchor = "nw", pady = 2, padx=10)
stock_label = Label(selector1Frame, text = "Select Stock / Time Interval / Series type / Moving average type / Fast Period / Slow Period :", background="white")
stock_label.pack(anchor="w") # the stock label

curr1 = tuple() # the tuple which will be populated by base and quote currency
currency_list = ['AUD', 'BCH', 'BNB', 'BND', 'BTC', 'CAD', 'CHF', 'CNY', 'EOS', 'EUR', 'ETH', 'GBP', 'HKD', 'JPY', 'LTC', 'NZD', 'MYR', 'TRX', 'USD', 'USDT', 'XLM', 'XRP'] # major world currency pairs

# populate the combo box for both the base and quote currency
for key in currency_list:
    curr1 += (key, )

# populate the stock symbol tuple
f = open("stock.txt", "r")
curr2 = tuple()
for line in f.readlines():
    curr2 += (line.replace('\n', ''),)
f.close()

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

# Create a combo box for quote currency
quote_currency = StringVar() # create a string variable
quote = tk.Combobox(selectorFrame, textvariable=quote_currency)
quote['values'] = curr1
quote.pack(side = LEFT, padx=3)

# Create a combo box for stock items
stock_symbol = StringVar() # create a string variable
stock = tk.Combobox(selector1Frame, textvariable=stock_symbol)
stock['values'] = curr2
stock.current(0)
stock.pack(side = LEFT, padx=3)

interval = tk.Combobox(selector1Frame)
interval['values'] = ('1min', '5min', '15min', '30min', '60min', 'daily', 'weekly', 'monthly')
interval.current(0)
interval.pack(side = LEFT, padx=3)

price_type = tk.Combobox(selector1Frame)
price_type['values'] = ('close', 'open', 'high', 'low')
price_type.current(0)
price_type.pack(side =LEFT, padx=3)

matype_type = tk.Combobox(selector1Frame, width=37)
matype_type['values'] = ('Simple Moving Average (SMA)', 'Exponential Moving Average (EMA)', 'Weighted Moving Average (WMA)', 'Double Exponential Moving Average (DEMA', 'Triple Exponential Moving Average (TEMA)', 'Triangular Moving Average (TRIMA', 'T3 Moving Average', 'Kaufman Adaptive Moving Average (KAMA)', ' MESA Adaptive Moving Average (MAMA)')
matype_type.current(0)
matype_type.pack(side =LEFT, padx=3)
mattype_list = ['Simple Moving Average (SMA)', 'Exponential Moving Average (EMA)', 'Weighted Moving Average (WMA)', 'Double Exponential Moving Average (DEMA', 'Triple Exponential Moving Average (TEMA)', 'Triangular Moving Average (TRIMA', 'T3 Moving Average', 'Kaufman Adaptive Moving Average (KAMA)', ' MESA Adaptive Moving Average (MAMA)']

# fill up the fast period and slow period combo boxes with integer ranging from 2 to 10,000
fa = tuple()
for i in range(2, 10001):
    fa += (i, )

fast_pe = tk.Combobox(selector1Frame)
fast_pe['values'] = fa
fast_pe.current(0)
fast_pe.pack(side=LEFT, padx=3)

slow_pe = tk.Combobox(selector1Frame)
slow_pe['values'] = fa
slow_pe.current(0)
slow_pe.pack(side=LEFT, padx=3)

# create text widget area
s = StringVar() # create string variable which will be used to fill up the Forex data
# create currency frame and text widget to display the incoming forex data
currencyFrame = Frame(win)
currencyFrame.pack(side=TOP, fill=X)
currency = Label(currencyFrame)
currency.pack(fill=X)
text_widget = Text(currency, fg='white', background='black')
text_widget.pack(fill=X)
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, padx=10)

# first get the api key and secret from the file
f = open("alpha.txt", "r")
api_key = f.readline()
f.close()
api_key = api_key.replace('\n', '')

def get_exchange_rate(): # this method will display the incoming forex data after the api called

    try:
        cc = ForeignExchange(key= api_key)
        from_ = based.get()
        to_ = quote.get()

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

        if(from_ != '' and to_ != '' and from_ != to_):
            data, _ = cc.get_currency_exchange_rate(from_currency=from_, to_currency=to_)
            exchange_rate = dict(json.loads(json.dumps(data)))
            count = 1
            sell_buy = str(count) + ".) Pair : " + exchange_rate['1. From_Currency Code'] + "(" + exchange_rate['2. From_Currency Name'] + ")" + " / " + exchange_rate['3. To_Currency Code']+"(" + exchange_rate['4. To_Currency Name'] + ") : "  + str(exchange_rate['5. Exchange Rate']) + '\n'
            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
            pos = text_widget.search(from_, "1.0", stopindex="end", count=countVar)
            text_widget.tag_configure("search", background="green")
            end_pos = float(pos) + float(0.7)
            text_widget.tag_add("search", pos, str(end_pos))  # highlight the background of the searched currency pair
            pos = float(pos) + 2.0
            text_widget.see(str(pos))

    except:
        print("An exception occurred")

def plot_stock_echange():

    try:
        stock_symbol_text = stock.get() # get the selected symbol
        if(stock_symbol_text!= ''):
            ts = TimeSeries(key=api_key, output_format='pandas')
            data, meta_data = ts.get_intraday(symbol=stock_symbol_text, interval='1min', outputsize='full')
            data['4. close'].plot()
            stock_title = 'Intraday Times Series for the ' + stock_symbol_text + ' stock (1 min)'
            plt.title(stock_title)
            plt.show()
    except:
        print("An exception occurred")

def plot_stock_technical():

    try:
        stock_symbol_text = stock.get() # get the selected stock symbol
        if(stock_symbol_text!= ''):

            ti = TechIndicators(key=api_key, output_format='pandas')
            data, meta_data = ti.get_bbands(symbol=stock_symbol_text, interval=interval.get(), series_type=price_type.get(), matype=mattype_list.index(matype_type.get()), time_period=int(interval.get().replace('min', '')))
            data.plot()
            stock_title = 'BBbands indicator for ' + stock_symbol_text + ' ' + interval.get()
            plt.title(stock_title)
            plt.show()
    except:
        print("An exception occurred")

def plot_op(): # plot the Absolute price oscillator (APO) graph

    try:
        stock_symbol_text = stock.get() # get the selected stock symbol
        if(stock_symbol_text!= ''):

            ti = TechIndicators(key=api_key, output_format='pandas')
            data, meta_data = ti.get_apo(symbol=stock_symbol_text, interval=interval.get(), series_type=price_type.get(), matype=mattype_list.index(matype_type.get()), fastperiod = fast_pe.get(), slowperiod= slow_pe.get())
            data.plot()
            stock_title = 'Absolute Price Oscillator (APO) for ' + stock_symbol_text + ' ' + interval.get()
            plt.title(stock_title)
            plt.show()
    except ValueError:
        print("An exception occurred")

def plot_adxr(): # plot the average directional movement index rating

    try:
        stock_symbol_text = stock.get() # get the selected stock symbol
        if(stock_symbol_text!= ''):

            ti = TechIndicators(key=api_key, output_format='pandas')
            data, meta_data = ti.get_adxr(symbol=stock_symbol_text, interval=interval.get(), time_period=int(interval.get().replace('min', '')))
            data.plot()
            stock_title = 'Average directional movement index rating for ' + stock_symbol_text + ' at ' + interval.get()
            plt.title(stock_title)
            plt.show()
    except ValueError:
        print("An exception occurred")

def plot_adx(): # plot the average directional movement index

    try:
        stock_symbol_text = stock.get() # get the selected stock symbol
        if(stock_symbol_text!= ''):

            ti = TechIndicators(key=api_key, output_format='pandas')
            data, meta_data = ti.get_adx(symbol=stock_symbol_text, interval=interval.get(), time_period=int(interval.get().replace('min', '')))
            data.plot()
            stock_title = 'Average directional movement index for ' + stock_symbol_text + ' at ' + interval.get()
            plt.title(stock_title)
            plt.show()
    except ValueError:
        print("An error exception occurred")

def plot_sector_performance():

    sp = SectorPerformances(key=api_key, output_format='pandas')
    data, meta_data = sp.get_sector()
    data['Rank A: Real-Time Performance'].plot(kind='bar')
    plt.title('Real Time Performance (%) per Sector')
    plt.tight_layout()
    plt.grid()
    plt.show()

def plot_ad():

    try:
        stock_symbol_text = stock.get()  # get the selected stock symbol
        if (stock_symbol_text != ''):
            ti = TechIndicators(key=api_key, output_format='pandas')
            data, meta_data = ti.get_ad(symbol=stock_symbol_text, interval=interval.get())
            data.plot()
            stock_title = 'Chaikin A/D line values for ' + stock_symbol_text + ' ' + interval.get()
            plt.title(stock_title)
            plt.show()
    except:
        print("An exception occurred")

def plot_aroon(): # plot the aroon values

    try:
        stock_symbol_text = stock.get() # get the selected stock symbol
        if(stock_symbol_text!= ''):

            ti = TechIndicators(key=api_key, output_format='pandas')
            data, meta_data = ti.get_aroon(symbol=stock_symbol_text, interval=interval.get(), series_type=price_type.get(), time_period=int(interval.get().replace('min', '')))
            data.plot()
            stock_title = 'The Aroon Up and the Aroon Down lines for ' + stock_symbol_text + ' ' + interval.get()
            plt.title(stock_title)
            plt.show()
    except ValueError:
        print("An exception occurred")

def plot_aroonosc(): # plot the aroon oscillator values

    try:
        stock_symbol_text = stock.get() # get the selected stock symbol
        if(stock_symbol_text!= ''):

            ti = TechIndicators(key=api_key, output_format='pandas')
            data, meta_data = ti.get_aroon(symbol=stock_symbol_text, interval=interval.get(), series_type=price_type.get(), time_period=int(interval.get().replace('min', '')))
            data.plot()
            stock_title = 'The aroon oscillator values for ' + stock_symbol_text + ' ' + interval.get()
            plt.title(stock_title)
            plt.show()
    except ValueError:
        print("An exception occurred")

def plot_atr(): # plot the average true range values

    try:
        stock_symbol_text = stock.get() # get the selected stock symbol
        if(stock_symbol_text!= ''):

            ti = TechIndicators(key=api_key, output_format='pandas')
            data, meta_data = ti.get_atr(symbol=stock_symbol_text, interval=interval.get(), time_period=int(interval.get().replace('min', '')))
            data.plot()
            stock_title = 'The average true range values line for ' + stock_symbol_text + ' ' + interval.get()
            plt.title(stock_title)
            plt.show()
    except ValueError:
        print("An exception occurred")

def plot_tr3(): # plot the triple exponential moving average time series graph

    try:
        stock_symbol_text = stock.get() # get the selected stock symbol
        if(stock_symbol_text!= ''):

            ti = TechIndicators(key=api_key, output_format='pandas')
            data, meta_data = ti.get_t3(symbol=stock_symbol_text, interval=interval.get(), series_type=price_type.get(), time_period=int(interval.get().replace('min', '')))
            data.plot()
            stock_title = 'The triple exponential moving average time series for ' + stock_symbol_text + ' ' + interval.get()
            plt.title(stock_title)
            plt.show()
    except ValueError:
        print("An exception occurred")

action_vid = tk.Button(buttonFrame, text="Calculate Exchange Rate", command=get_exchange_rate) # button used to find out the exchange rate of currency pair
action_vid.pack(side=LEFT, padx=2)
action_stock_plot = tk.Button(buttonFrame, text="Plot Stock", command=plot_stock_echange) # button used to plot the intra-minute stock value
action_stock_plot.pack(side=LEFT, padx=2)
action_technical_plot = tk.Button(buttonFrame, text="Plot Technical", command=plot_stock_technical) # button used to plot the 60 minutes stock technical value
action_technical_plot.pack(side=LEFT, padx=2)
action_sector_plot = tk.Button(buttonFrame, text="Plot Sector Performance", command=plot_sector_performance) # button used to plot the sector performance graph
action_sector_plot.pack(side=LEFT, padx=2)
action_ad_plot = tk.Button(buttonFrame, text="Plot AD Line", command=plot_ad) # button used to plot the A/D line graph
action_ad_plot.pack(side=LEFT, padx=2)
action_ad_op = tk.Button(buttonFrame, text="Plot APO Line", command=plot_op) # button used to plot the APO line graph
action_ad_op.pack(side=LEFT, padx=3)
action_adxr = tk.Button(buttonFrame, text="Plot ADXR Line", command=plot_adxr) # button used to plot the average directional movement index rating
action_adxr.pack(side=LEFT, padx=3)
action_adx = tk.Button(buttonFrame, text="Plot ADX Line", command=plot_adx) # button used to plot the average directional movement index
action_adx.pack(side=LEFT, padx=3)
action_aroon = tk.Button(buttonFrame, text="Plot Aroon Line", command=plot_aroon) # button used to plot the aroon values
action_aroon.pack(side=LEFT, padx=3)
action_aroonosc = tk.Button(buttonFrame, text="Plot Aroon Oscillator Line", command=plot_aroonosc) # button used to plot the aroon oscillator values
action_aroonosc.pack(side=LEFT, padx=3)
action_atr = tk.Button(buttonFrame, text="Plot ATR Line", command=plot_atr) # button used to plot the average true range line
action_atr.pack(side=LEFT, padx=3)
action_t3 = tk.Button(buttonFrame, text="Plot T3 Line", command=plot_tr3) # button used to plot the triple exponential moving average time series line
action_t3.pack(side=LEFT, padx=3)

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

With that, we have concluded the final chapter for this project, there are more alpha vantage APIs that you can use to display more data of a Stock or Forex, all you need to do is to sign up for a free API key from the alpha vantage main page. After the end of this project, I will update this site once a week if there is any new project which I have created during that week. Do consider donating to this site to help me to ease the cost of web hosting if you can, thank you very much!



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...