Código de Python - Visor de gráficos financieros (nueva versión)

Imágen de perfil
Val: 712
Bronce
Ha aumentado 1 puesto en Python (en relación al último mes)
Gráfica de Python

Visor de gráficos financieros (nueva versión)gráfica de visualizaciones


Python

Actualizado el 11 de Abril del 2024 por Antonio (76 códigos) (Publicado el 18 de Abril del 2022)
3.333 visualizaciones desde el 18 de Abril del 2022
Programa para mostrar el precio de cierre, apertura, máximo y mínimo de las acciones de un activo para un determinado periodo de tiempo. También incluye representación de 'bandas de bollinger' y la media movil de 20 sesiones. Para mostrar la gráfica correspondiente a la información deseada, hacer click en el botón 'SHOW GRAPH'. Para cualquier duda u observación, utilicen la sección de comentarios.
fg

Requerimientos

Librerias y recursos: ta, tkinter, datetime, os, threading, matplotlib, yfinance (version 0.2.3)

2.0
estrellaestrellaestrellaestrellaestrella(1)

Actualizado el 6 de Noviembre del 2022 (Publicado el 18 de Abril del 2022)gráfica de visualizaciones de la versión: 2.0
1.787 visualizaciones desde el 18 de Abril del 2022
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
!/usr/bin/env python
# -*- coding: utf-8 -*-
import pickle
import ta
from ta.utils import dropna
import yfinance as yf
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox, filedialog
import tkinter.scrolledtext as sct
import datetime as date
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
import matplotlib.animation as animation
from matplotlib import style
import threading
import os
import warnings
warnings.filterwarnings("ignore")
 
if not 'symbols' in os.listdir():
    fichero = open('symbols','wb')
    pickle.dump([],fichero)
    fichero.close()
 
now = datetime.now()
previous = now - timedelta(days = 500)
 
style.use('dark_background')
root = tk.Tk()
root.title("Finan Graph 4")
root.configure(background="gray")
root.geometry("1160x800")#1160
start_date = tk.StringVar()
end_date = tk.StringVar()
df = ""
table_head = ""
used_symbols = sorted(pickle.load(open("symbols","rb")))
actv = False
fig = Figure()
ax1 = fig.add_subplot(111)
ax1.grid()
selected_items = ["Close"]
special_metrics = []
 
canvas = FigureCanvasTkAgg(fig,master=root)
canvas.draw()
toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()
canvas.get_tk_widget().pack(side=tk.BOTTOM,fill=tk.BOTH, expand=1)
 
def show_info():
    if tick_entry.get() != "":
        try:
            tic = yf.Ticker(tick_entry.get())
            topp = tk.Toplevel()
            topp.title("MORE INFO")
            display = sct.ScrolledText(master=topp,width=95,height=30)
            display.pack(padx=0,pady=0)
            display.insert(tk.END,"COLLECTING INFO...")
            final = tic.info
            display.delete('1.0',tk.END)
            display.insert(tk.END,tick_entry.get()+"\n\n")
            for key, value in final.items():
                display.insert(tk.END,key+":"+"\n"+str(value)+"\n\n")
 
        except Exception as e:
            messagebox.showwarning("UNEXPECTED ERROR",str(e))
    else:
        messagebox.showwarning("EMPTY","No info to show.")
 
def save_table():
    doc = filedialog.asksaveasfilename(initialdir="/",
                title="Save",defaultextension='.txt')
    if doc != "":
        with open(doc,"w") as document:
            document.write(table_head+"\n\n"+str(df))
        messagebox.showinfo("SAVED","Document saved")
 
def valid_date(char):
    return char in "0123456789/"
 
def show_table():
    if str(df) != "":
        if df.empty == False:
            top = tk.Toplevel()
            top.title("INFO TABLE")
            tk.Button(top,text="SAVE TABLE",command=save_table).pack(side=tk.BOTTOM)
            display = sct.ScrolledText(master=top,width=90,height=20)
            display.pack(padx=0,pady=0)
            display.insert(tk.END,table_head+"\n\n"+str(df))
        else:
            messagebox.showwarning("INVALID TICKER",str(df)+"\n"+"Enter a valid ticker.")
    else:
        messagebox.showwarning("EMPTY","No data to show.")
 
def selection(n,l):
    global selected_items, special_metrics
    if n not in l:
        l.append(n)
        buttons[n].configure(bg="light green")
    else:
        l.remove(n)
        buttons[n].configure(bg="light gray")
    if selected_items == []:
        selected_items.append('Close')
        buttons['Close'].configure(bg="light green")
    print("S. Items:",selected_items)
    print("Sp. Metrics:",special_metrics)
 
def make_graph():
    global actv, df, table_head
    print("ACTIVATED")
    try:
        ticker = tick_entry.get()
        if ticker != "" and end_datee.get() != "" and sts_entry.get() != "":
            ax1.clear()
            ax1.grid()
            e_date = end_datee.get().split("/")
            s_date = sts_entry.get().split("/")
            enddate = date.datetime(int(e_date[0]),int(e_date[1]),int(e_date[2]))
            startdate = date.datetime(int(s_date[0]),int(s_date[1]),int(s_date[2]))
 
            #--------------------------------------------------------------------------------------------------
            df = yf.Ticker(ticker).history(start=startdate,end=enddate).reset_index()[['Date']+selected_items]
 
            if df.empty == False:
                df = dropna(df)
                if len(special_metrics)>0:
                    if not "Close" in selected_items:
                        selected_items.append("Close")
                        btnClose.configure(bg="light green")
                        df = yf.Ticker(ticker).history(start=startdate,end=enddate).reset_index()[['Date']+selected_items]
                        ax1.plot(df["Date"],df["Close"])
                    bol = ta.volatility.BollingerBands(df["Close"], window=20)
                    for e in special_metrics:
                        selected_items.append(e)
                    if "M-AVG" in selected_items:
                        df['M-AVG'] = bol.bollinger_mavg()#media movil
                    if "BOLL. BANDS" in selected_items:
                        selected_items.remove("BOLL. BANDS")
                        df['High Band'] = bol.bollinger_hband()#banda superior
                        selected_items.append('High Band')
                        df['Low Band'] = bol.bollinger_lband()
                        selected_items.append('Low Band')#banda inferior
                update_tickers(ticker)
 
                #---------------------------------------------------------------------------------------------------
 
                table_head = "{} ({}-{})".format(ticker,sts_entry.get(),end_datee.get())
 
                for i in selected_items:
                    if i == 'Low Band' or i == 'High Band':
                        ax1.plot(df["Date"],df[i],color="purple")
                    else:
                        ax1.plot(df["Date"],df[i])
 
                ax1.set_title(table_head)
                ax1.legend(selected_items,loc='best', shadow=False)
                ax1.set_ylabel("PRICE")
                ax1.set_xlabel("TIME")
            else:
                messagebox.showwarning("INVALID TICKER",str(df)+"\n"+"Enter a valid ticker.")
 
 
        else:
            messagebox.showwarning("NO TICKER OR PERIOD PROVIDED","Please, select ticker and time interval.")
 
    except Exception as e:
        messagebox.showwarning("UNEXPECTED ERROR",str(e))
 
    actv = False
    print(selected_items)
    deling = ["M-AVG","BOLL. BANDS","Low Band","High Band"]
    for i in deling:
        if i in selected_items:
            selected_items.remove(i)
 
    print(selected_items)
 
def activate():
    global actv
    actv = True
 
def update_tickers(t):
    if t not in used_symbols:
        used_symbols.insert(0,tick_entry.get())
        pickle.dump(used_symbols,open("symbols","wb"))
        tick_entry["values"]=pickle.load(open("symbols","rb"))
 
def init_task():
    t = threading.Thread(target=show_info)
    t.start()
 
def represent(i):
    global actv
    if actv == True:
        make_graph()
 
tick_entry = ttk.Combobox(root,width=10)
tick_entry["values"]=used_symbols
tick_entry.place(x=50,y=8)
tk.Label(root,height=2,bg="gray").pack(side=tk.LEFT)
tk.Label(root,text="TICKER:",bg="gray",fg="white").place(x=3,y=8)
tk.Label(root,text="START DATE:",bg="gray",fg="white").place(x=135+11,y=8)
tk.Label(root,text="END DATE:",bg="gray",fg="white").place(x=296,y=8)
validate_entry = root.register(valid_date)
sts_entry = tk.Entry(root,textvariable=start_date,width=10,validate="key",validatecommand=(validate_entry, "%S"))
sts_entry.place(x=210+11,y=8)
start_date.set("{}/{}/{}".format(previous.year,previous.month,previous.day))
end_datee = tk.Entry(root,textvariable=end_date,width=10,validate="key",validatecommand=(validate_entry, "%S"))
end_datee.place(x=362,y=8)
end_date.set("{}/{}/{}".format(now.year,now.month,now.day))
btnHigh = tk.Button(root,text="High",bg="gray83",width=5,command=lambda:selection("High",selected_items))
btnHigh.place(x=450,y=5)
btnLow = tk.Button(root,text="Low",bg="gray83",width=5,command=lambda:selection("Low",selected_items))
btnLow.place(x=497,y=5)
btnOpen = tk.Button(root,text="Open",bg="gray83",width=5,command=lambda:selection("Open",selected_items))
btnOpen.place(x=544,y=5)
btnClose = tk.Button(root,text="Close",bg="light green",width=5,command=lambda:selection("Close",selected_items))
btnClose.place(x=591,y=5)
btnMA = tk.Button(root,text="MAVG 20",bg="gray83",width=12,command=lambda:selection("M-AVG",special_metrics))
btnMA.place(x=770,y=5)
btnBol = tk.Button(root,text="BOLL. BANDS",bg="gray83",width=12,command=lambda:selection("BOLL. BANDS",special_metrics))
btnBol.place(x=674,y=5)
tk.Button(root,text="SHOW INFO",bg="gray83",command=init_task).pack(side="right",padx=2)
tk.Button(root,text="SHOW TABLE",bg="gray83",command=show_table).pack(side="right",padx=2)
tk.Button(root,text="SHOW GRAPH",bg="gray83",command=activate).pack(side="right",padx=2)
 
ani = animation.FuncAnimation(fig, represent, interval=1000)
buttons = {"High":btnHigh,"Low":btnLow,"Open":btnOpen,"Close":btnClose,"M-AVG":btnMA,"BOLL. BANDS":btnBol}
 
root.mainloop()



Comentarios sobre la versión: 2.0 (1)

26 de Agosto del 2022
estrellaestrellaestrellaestrellaestrella
hola, estaba probando tu codigo,., y por alguna razon....no me reconoce donde van los ticker a seleccionar
Responder

Comentar la versión: 2.0

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

2.1

Actualizado el 11 de Abril del 2024 (Publicado el 25 de Enero del 2023)gráfica de visualizaciones de la versión: 2.1
1.547 visualizaciones desde el 25 de Enero del 2023
http://lwp-l.com/s7226