'Candlestick graph in tkinter canvas/frame
I am trying to create a candlestick chart into tkinter. I have main window top, and I am creating a frame (graph_frame) at specific location. After click of a button, I want to place my candlestick chart into that frame. I am running followed code, but instead of placing chart into frame, the chart gets displayed in jupyter notebook output. I want to place this chart into my tkinter window and the specific canvas frame I created.
from tkinter import *
#import Pmw
import urllib.request
import urllib.parse
from datetime import date
from io import StringIO
import datetime
from datetime import datetime
import requests
import pandas as pd
import arrow
import datetime
import sys
import json
import yfinance as yf
import plotly.graph_objects as go
import numpy as np
import csv
import matplotlib.pyplot as plt
import plotly.graph_objects as go
import quandl as ql
from matplotlib import dates
%matplotlib inline
import matplotlib.dates as mpdates
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,NavigationToolbar2Tk
import tkinter as tk
from tkinter import ttk
import mplfinance as mpf
import matplotlib.pyplot as plt
from mpl_finance import candlestick_ohlc
import pandas as pd
import matplotlib.dates as mpl_dates
top = tk.Tk()
top.title("NASDAR Stock price range prediction system")
top.geometry("1350x840")
graph_frame = tk.Frame(top, height=350, width=500)
graph_frame.place(x=700,y=250)
figure = plt.Figure(figsize=(12,8), dpi=50)
ax = figure.add_subplot(111)
df = yf.download('ba', period='500d', interval='1d')
df = df.tail(50)
df['Date'] = pd.to_datetime(df['Date'])
# apply map function
df['Date'] = df['Date'].map(mpdates.date2num)
fig, ax = plt.subplots()
fig = FigureCanvasTkAgg(fig, graph_frame)
# plotting the data
candlestick_ohlc(ax, df.values, width = 0.6,colorup = 'green', colordown = 'red', alpha = 0.8)
ohlc = df.loc[:, ['Date', 'Open', 'High', 'Low', 'Close']]
ohlc['Date'] = pd.to_datetime(ohlc['Date'])
ohlc['Date'] = ohlc['Date'].apply(mpl_dates.date2num)
ohlc = ohlc.astype(float)
ax.set_xlabel('Date')
ax.set_ylabel('Price')
# Formatting Date
date_format = mpl_dates.DateFormatter('%d-%m-%Y')
ax.xaxis.set_major_formatter(date_format)
ax.set_title('Candlestick chart')
Solution 1:[1]
Followed code worked and I am able to generate graphs into my specific frame in tkinter. graph_frame has been declared in the beginning in main function.
figure = plt.Figure(figsize=(3,4), dpi=100)
#data = yf.download(symbol, period='500d', interval='1d')
data = yf.download('ba', period='500d', interval='1d')
df = convert_to_dataframe_daily(data)
#df = return_data_frame()
df['Date'] = pd.to_datetime(df['Date'])
df['SMA5'] = df['Close'].rolling(5).mean()
df = df.tail(15)
# apply map function
df['Date'] = df['Date'].map(mpdates.date2num)
figure, ax = plt.subplots()
fig = FigureCanvasTkAgg(figure, graph_frame)
ax.set_xlabel('Date')
ax.set_ylabel('Price')
#fig.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH)
fig.get_tk_widget().pack(side=tk.RIGHT)
# plotting the data
candlestick_ohlc(ax, df.values, width = 0.6,colorup = 'green', colordown = 'red', alpha = 0.8)
ohlc = df.loc[:, ['Date', 'Open', 'High', 'Low', 'Close']]
#ohlc['Date'] = pd.to_datetime(ohlc['Date'])
#ohlc['Date'] = ohlc['Date'].apply(mpl_dates.date2num)
#ohlc = ohlc.astype(float)
print(ohlc.tail(10))
#fig.suptitle('Daily Candlestick Chart of NIFTY50')
# Formatting Date
date_format = mpl_dates.DateFormatter('%d-%m-%Y')
ax.xaxis.set_major_formatter(date_format)
ax.plot(df['Date'], df['EMA21'], color='green', label='EMA 21', linewidth=0.5)
ax.plot(df['Date'], df['EMA8'], color='blue', label='EMA 8', linewidth=0.5)
ax.plot(df['Date'], df['SMA200'], color='darkorange', label='SMA 200', linewidth=1.5)
ax.grid(True)
ax.set_title('Candlesticks with moving averages')
```
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharmesh |
