Exception in Tkinter when information is displayed

43 views Asked by At

I'm bringing an information from yfinance using python 3.11 (I'm using tensorflow which not yet is available for version 3.12) This is the structure of my application:

import os
import numpy as np
import pandas as pd
from sklearn.feature_selection import SelectKBest, f_regression
import yfinance as yf
import tkinter as tk
from tkinter import ttk
from datetime import datetime
from tkinter import messagebox
from sklearn.model_selection import GridSearchCV, cross_val_score, train_test_split
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.svm import SVR
from sklearn.metrics import mean_squared_error
from ta.volatility import BollingerBands
from ta.trend import SMAIndicator, MACD
from ta.momentum import RSIIndicator

from dotenv import load_dotenv


load_dotenv()

class StockAnalysisApp:

Now self.data is an atribute assigned when obtener_datos_criptomoneda() function is executed:

    def obtener_datos_criptomoneda(self, activo, periodo, temporalidad):
        data_yfinance = yf.download(activo, interval=temporalidad, period=periodo)
        self.data = data_yfinance.dropna()
        #Crear carperta si no existe
        carpeta_activo = os.path.join(os.getenv('CRYPTO_PATH_DATA'), activo)
        self.crear_directorios(carpeta_activo)
        #Guardar archivo CSV
        ruta_archivo = os.path.join(carpeta_activo, f'{activo}_{temporalidad}.csv')
        self.data.to_csv(ruta_archivo, sep=';', decimal=',')

For this data the column 'Date' doesn't exists, The Date column is indexed within the data and can be accessed using data.index, I'm trying to show this information into a table but I'm having issues to access the date info

        for i in reversed(range(len(self.data))):
            self.data_table.insert("", tk.END, values=(
                   {self.data.index.iloc[i]},
                f'${self.data["Open"].iloc[i]:.2f}',
                f'${self.data["Close"].iloc[i]:.2f}',
                f'${self.data["Low"].iloc[i]:.2f}',
                f'${self.data["High"].iloc[i]:.2f}',
                f'${self.data["Adj Close"].iloc[i]:.2f}',
                f'{self.data["Volume"].iloc[i]:.2f}'
            ))

I'm expecting that the date can be displayed in the table created for it, here is where I created the table in the class within the init()

class StockAnalysisApp:
    def __init__(self, root, crear_ruta):

        scroll_x = tk.Scrollbar(self.center_frame, orient="horizontal")
        scroll_x.pack(side=tk.BOTTOM, fill=tk.X)
        scroll_y = tk.Scrollbar(self.center_frame, orient="vertical")
        scroll_y.pack(side=tk.RIGHT, fill=tk.Y)
        #Widgets en el marco central tabla para mostrar datos
        self.data_table = ttk.Treeview(self.center_frame, columns=["Date", "Open","High", "Low","Close", "Adj Close", "Volume"], show="headings")
        self.data_table.heading("Date", text="Date")
        for col in ("Open","High", "Low","Close", "Adj Close", "Volume"):
            self.data_table.heading(col, tex=col, anchor=tk.CENTER)
            self.data_table.column(col, anchor=tk.E) #Alineacion a la derecha

        for col in ["Date", "Open","High", "Low","Close", "Adj Close", "Volume"]:
            self.data_table.heading(col, text=col, anchor=tk.CENTER)
            self.data_table.column(col, anchor=tk.CENTER, width=100)#Ajustar el ancho de cada columna para que se ajuste a la ventana
        #Configurar barras de desplazamiento
        scroll_x.config(command=self.data_table.xview)
        scroll_y.config(command=self.data_table.yview)

        self.data_table.config(xscrollcommand=scroll_x.set, yscrollcommand=scroll_y.set)

        self.data_table.pack(pady=20, padx=20, fill=tk.BOTH, expand=True)
2

There are 2 answers

0
Will Diaz On

Actually it was a bad access to the information in the for loop I just need to access the date this way

        for i in reversed(range(len(self.data))):
            self.data_table.insert("", tk.END, values=(
                   datetime.strftime(self.data.index[i],'%Y/%m/%d'),
                f'${self.data["Open"].iloc[i]:.2f}',
                f'${self.data["Close"].iloc[i]:.2f}',
                f'${self.data["Low"].iloc[i]:.2f}',
                f'${self.data["High"].iloc[i]:.2f}',
                f'${self.data["Adj Close"].iloc[i]:.2f}',
                f'{self.data["Volume"].iloc[i]:.2f}'
            ))
0
NoRealOwner On

Since the date information is in the index of your dataframe I mean data.index you can access it directly. Can you try this one:

for i in reversed(range(len(self.data))):
date_str = self.data.index[i].strftime('%Y-%m-%d')  
self.data_table.insert("", tk.END, values=(
    date_str,
    f'${self.data["Open"].iloc[i]:.2f}',
    f'${self.data["Close"].iloc[i]:.2f}',
    f'${self.data["Low"].iloc[i]:.2f}',
    f'${self.data["High"].iloc[i]:.2f}',
    f'${self.data["Adj Close"].iloc[i]:.2f}',
    f'{self.data["Volume"].iloc[i]:.2f}'
))