Código de Python - Visor de gráficos financieros.

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.gráfica de visualizaciones


Python

Actualizado el 1 de Abril del 2024 por Antonio (75 códigos) (Publicado el 7 de Julio del 2021)
9.188 visualizaciones desde el 7 de Julio del 2021
El programa muestra información relativa al precio máximo, mínimo, de apertura y cierre de un activo financiero (estos se irán almacenando en el archivo "symbols" que se generará al ejecutar el programa por primera vez) y para un periodo de tiempo. También muestra los gráficos relativos a las medias móviles exponenciales de 50 y 200 sesiones.
PARA CUALQUIER DUDA U OBSERVACIÓN USEN LA SECCIÓN DE COMENTARIOS.
gf

Requerimientos

Python 3
yfinance 0.1.62

0.3

Actualizado el 9 de Julio del 2021 (Publicado el 7 de Julio del 2021)gráfica de visualizaciones de la versión: 0.3
404 visualizaciones desde el 7 de Julio del 2021

1.0
estrellaestrellaestrellaestrellaestrella(2)

Actualizado el 9 de Noviembre del 2021 (Publicado el 9 de Julio del 2021)gráfica de visualizaciones de la versión: 1.0
2.534 visualizaciones desde el 9 de Julio del 2021
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

Visualización de la evolución del precio de un valor a determinar por el usuario, para un periodo también a determinar por usuario (establecido por defecto, para 400 sesiones desde la fecha actual). Puede mostrar la evolución diaria de los precios máximo, mínimo, de apertura y cierre. También puede mostrar las medias móviles exponenciales de 50 y 200 sesiones. Para ver la información seleccionada pinchar en el botón "SHOW GRAPH". El botón "SHOW TABLE", muestra una tabla con los primeros y últimos valores de la serie temporal escogida.
PARA CUALQUIER DUDA U OBSERVACIÓN, USEN LA SECCIÓN DE COMENTARIOS.
fg2
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
from pandas_datareader import data as pdr
import pickle
import yfinance as yf
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
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 os
import numpy as np
 
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()
root.title("Finan Graph 5")
root.configure(background="gray")
root.geometry("1160x800")
start_date = StringVar()
end_date = StringVar()
df2 = ""
table_head = ""
used_symbols = sorted(pickle.load(open("symbols","rb")))
actv = False
fig = Figure()
ax1 = fig.add_subplot(111)
ax1.set_ylabel("PRICE")
ax1.set_xlabel("TIME (YYYY-MM)")
ax1.grid()
selected_items = ["Close"]
item_list = ["Low","High","Open","Close","EMA_50","EMA_200"]
 
canvas = FigureCanvasTkAgg(fig,master=root)
canvas.draw()
toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()
canvas.get_tk_widget().pack(side=BOTTOM,fill=BOTH, expand=1)
 
def activate():
    global actv
    actv = True
 
def show_table():
    if str(df2) != "":
        top = Toplevel()
        top.title("INFO TABLE")
        display = sct.ScrolledText(master=top,width=90,height=20)
        display.pack(padx=0,pady=0)
        display.insert(END,table_head+"\n\n"+str(df2))
    else:
        messagebox.showwarning("EMPTY","No data to show.")
 
 
def EMA(df, n):
    EMA = pd.Series(pd.Series.ewm(df['Close'],span = n, min_periods = n-1, adjust=False).mean(), name='EMA_'+str(n))
    df = df.join(EMA)
    return df
 
def selection(n):
    global selected_items
    if n not in selected_items:
        selected_items.append(n)
        buttons[n].configure(bg="light green")
    else:
        selected_items.remove(n)
        buttons[n].configure(bg="light gray")
 
def validate_date(l):
    if int(l[2]) <= 1 and int(l[1]) <= 1 and int(l[0]) <= 1970:
        return None
    else:
        return l
 
def make_graph():
    try:
        global actv, df2, table_head
        variables = []
        ax1.clear()
        ax1.grid()
        end_list= validate_date(end_datee.get().split("/"))#2019,11,1
        start_list= validate_date(sts_entry.get().split("/"))#2010,1,1
 
        if end_list is not None and start_list is not None:
            enddate = date.datetime(int(end_list[0]),int(end_list[1]),int(end_list[2]))
            startdate = date.datetime(int(start_list[0]),int(start_list[1]),int(start_list[2]))
            tick = tick_entry.get()
            yf.pdr_override()
            ipc = pdr.get_data_yahoo(tick, start = startdate, end = enddate)
            #print("MY INFO: ",ipc)
            if not "Empty DataFrame" in str(ipc):
                df = EMA(ipc, 50)
                df2 = EMA(df, 200)
                for i in item_list:
                    if i in selected_items:
                        variables.append(i)
                df2 = df2[variables]
                for i in df2:
                    ax1.plot(df2[i])
                ax1.legend(variables,loc='best', shadow=False)
                ax1.set_ylabel("PRICE")
                ax1.set_xlabel("DATES")
                table_head = "{} ({}-{})".format(tick,sts_entry.get(),end_datee.get())
                ax1.set_title(table_head)
                update_tickers(tick)
            else:
                messagebox.showwarning("NO DATA",str(ipc))
        else:
            messagebox.showwarning("ERROR","Bad date")
 
    except Exception as e:
        messagebox.showwarning("UNEXPECTED ERROR",str(e))
    actv = False
 
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 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)
Label(root,height=2,bg="gray").pack(side=LEFT)
Label(root,text="TICKER:",bg="gray",fg="white").place(x=3,y=8)
Label(root,text="START DATE:",bg="gray",fg="white").place(x=135+11,y=8)
Label(root,text="END DATE:",bg="gray",fg="white").place(x=296,y=8)
sts_entry = Entry(root,textvariable=start_date,width=10)
sts_entry.place(x=221,y=8)
start_date.set("{}/{}/{}".format(previous.year,previous.month,previous.day))
end_datee = Entry(root,textvariable=end_date,width=10)
end_datee.place(x=362,y=8)
end_date.set("{}/{}/{}".format(now.year,now.month,now.day))
btnHigh = Button(root,text="High",bg="gray83",command=lambda:selection("High"),width=5)
btnHigh.place(x=450,y=5)
btnLow = Button(root,text="Low",bg="gray83",command=lambda:selection("Low"),width=5)
btnLow.place(x=497,y=5)
btnOpen = Button(root,text="Open",bg="gray83",command=lambda:selection("Open"),width=5)
btnOpen.place(x=544,y=5)
btnClose = Button(root,text="Close",bg="light green",command=lambda:selection("Close"),width=5)
btnClose.place(x=591,y=5)
btnEMA50 = Button(root,text="EMA 50",bg="gray83",command=lambda:selection("EMA_50"),width=8)
btnEMA50.place(x=650,y=5)
btnEMA200 = Button(root,text="EMA 200",bg="gray83",command=lambda:selection("EMA_200"),width=8)
btnEMA200.place(x=716,y=5)
Button(root,text="SHOW TABLE",bg="gray83",command=show_table).pack(side="right",padx=2)
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,"EMA_50":btnEMA50,"EMA_200":btnEMA200}
root.mainloop()



Comentarios sobre la versión: 1.0 (2)

Juan Quintanilla
8 de Septiembre del 2021
estrellaestrellaestrellaestrellaestrella
Buenas noches, llevo unas semanas aprendiendo Python y en estas 2 semanas me estoy dedicando a aprender como manejar diversas librerías y me llamo la atención esta de yfinance y decidí usar tu código para aprender.

Desafortunadamente no entiendo como exportar la información de la empresa que quiero visualizar. Estuve revisando tutoriales pero no logro comprender como guardar los datos del TICKER para que así pueda seleccionarlos.

Me ayudarías mucho si me explicas brevemente como en tu código se exporta la información de una empresa para visualizarla como grafico (ya que no entiendo en que parte va). De antemano, muchas gracias.
Responder
Imágen de perfil
8 de Septiembre del 2021
estrellaestrellaestrellaestrellaestrella
No ha dejado ningún comentario
Responder

Comentar la versión: 1.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

1.1

Publicado el 9 de Noviembre del 2021gráfica de visualizaciones de la versión: 1.1
747 visualizaciones desde el 9 de Noviembre del 2021

2.1

Actualizado el 13 de Agosto del 2023 (Publicado el 22 de Diciembre del 2021)gráfica de visualizaciones de la versión: 2.1
3.891 visualizaciones desde el 22 de Diciembre del 2021

2.2

Actualizado el 1 de Abril del 2024 (Publicado el 23 de Agosto del 2023)gráfica de visualizaciones de la versión: 2.2
1.613 visualizaciones desde el 23 de Agosto del 2023
http://lwp-l.com/s7117