Getting error message when add the 'Ticker' in dataframe

Refer to the code below:

def layout(ticker=None, **other_unknown_query_strings):

    # get data for stock ticker from yahoo finance
    df = yf.Ticker(ticker).history(period="12mo").reset_index()
    df["Date"] = pd.to_datetime(df["Date"])

How about can I apply the same in the dataframe if I change the data location which is come from the excel csv instead of yahoo finance. I had tried but will getting an error message

AttributeError: ‘DataFrame’ object has no attribute ‘Ticker’

code I tried:

def layout(ticker= None, **other_unknown_query_strings):
    dff = pd.read_csv("dummy2.csv")
    df = dfk.Ticker(ticker).reset_index()


Expected output:

When user click the ‘Microsoft’, the another page will display the ‘Microsoft’ information in graph and table format.

image


image

1 Like

hi @beginof
when i get these error messages, it’s usually because that column (Ticker) does not exist. Could it be ticker with a small t? Or does the column have a different name?

Hi @adamschroeder,

Ya, is my fault.
Already change to ticker.

However, getting another error message :sob: :sob:

TypeError: ‘Series’ object is not callable

where is that error coming from, inside the callback?

yes, callback

  • ile “C:\ProgramData\Anaconda3\Lib\site-packages\dash\dash.py”, line 2087, in update

  layout(**path_variables, **query_parameters)


   df = dfk.Ticker(ticker)

TypeError: ‘Series’ object is not callable

Attached the code.

app.py

import plotly.express as px
from plotly.offline import plot

import dash
from dash import dcc, html, callback
# import dash_core_components as dcc
# import dash_html_components as html
from dash.dependencies import Output,Input, State
import dash_bootstrap_components as dbc
from dash import dash_table
from dash_table import DataTable, FormatTemplate


import pandas as pd
import pandas_datareader.data as web


from datetime import date, datetime


import pyodbc
import os
import psycopg2

from plotly.io import write_image
import flask
import base64





# Dashboard layout
app= dash.Dash(__name__,external_stylesheets=[dbc.themes.BOOTSTRAP],
                meta_tags=[{'name': 'viewport',
                            'content': 'width=device-width, initial-scale=1.0'}],
                use_pages=True,
                suppress_callback_exceptions=True,
                )



app.layout = dbc.Container([
    
    # dcc.Store(id = 'store'),
    dbc.Row([
        html.Div([
            dcc.Link(f"{page['name']}", href= page['path']) for page in dash.page_registry.values()
            
            ])
        
        ]),
    
    
    
    dbc.Row([#html.H5('test'),
              dash.page_container
        ]),
    ],
    fluid = True
    
    
    )      

if __name__ == "__main__":
    app.run_server(debug=True, port=1017)


page1.py

import plotly.express as px
from plotly.offline import plot

import dash
from dash import dcc, html, callback
# import dash_core_components as dcc
# import dash_html_components as html
from dash.dependencies import Output,Input, State
import dash_bootstrap_components as dbc
from dash import dash_table
from dash_table import DataTable, FormatTemplate
import dash_bootstrap_components as dbc

import pandas as pd
import pandas_datareader.data as web


from datetime import date, datetime


import pyodbc
import os
import psycopg2

from plotly.io import write_image
import flask
import base64


df= pd.read_csv("dummy2.csv")


df['year1'] = pd.to_datetime(df['Date'], format = '%d/%m/%Y', errors='coerce').dt.year
df['date1'] = pd.to_datetime(df['Date'], format = '%d/%m/%Y', errors='coerce')
df['date2'] = pd.to_datetime(df['Date'], format = '%d/%m/%Y', errors='coerce').dt.date
df['day1'] = pd.to_datetime(df['Date'], format = '%d/%m/%Y', errors='coerce').dt.day


product_cat = list(df['Product'].unique()) 

prod2 = tuple(list(df['Product'].unique()) )



df2 = df.copy()
df2.sort_values(by= ['Merchant ID','Product', 'Tnx Date', ], inplace = True)         
merchant_cat = list(df2['Merchant ID'].unique()) 

 
dash.register_page(__name__, 
                   # path_template='/details/<ticker>',
                   path="/",
                   title= 'Main')



        
layout = dbc.Container([
    
    # dcc.Store(id = 'store', storage_type = 'session'), #data={} , data=df.to_dict("records")
    # dcc.Store(id = 'store1', storage_type = 'session'),
    dbc.Row([
        dbc.Col(html.H1("Tes", #"Transaction Inquiry"
                        className = 'text-center text-primary, mb-4 '
                        ,style={"textDecoration":"underline",'font-weight': 'bold'}),
                width=12
                ),
      
        ]),
    html.Br(),
    html.Br(),
    
    # dbc.Row([utils.drop,
    #          utils.page_input]),
    
    
    dbc.Row([
        dbc.Col([
            html.H3('Product'
                    ,style={'font-size': '25px'}
                    ),
           
            ], width=3, md=4),
       
        dbc.Col([            
            dcc.Dropdown(id='product_dd', value= None, 
                          options = [{'label':x, 'value':x} 
                                    for x in product_cat],
                          
                          searchable = True, search_value='',
                          placeholder= 'Please select ...',
                          clearable= True,
                          persistence = True,
                          persistence_type = 'memory',
                          ),
           
            ], width=3, md=4),    
       
       
        ]),
    html.Br(),
    
    
    
    dbc.Row([       
        dbc.Col([            
            html.H3('Date'
                    ,style={'font-size': '25px'}
                    ),
            
            ], width=3, md=4),
    
        dbc.Col([            
            dcc.Dropdown(id='date_dd', value= '',                         
                          searchable = True, search_value='',
                          placeholder= 'DD/MM/YYYY',
                          clearable=True,
                          persistence = True,
                          persistence_type = 'memory',
                          
                          ),
                    
            ], width=3, md=4),
        
        dbc.Col([            
            html.H3('i.e: 15/11/2022'
                    ,style={'font-size': '15px'}
                    ),
            
            ], width=3, md=4),
        ], ), #style={"flexWrap": "wrap", "width":"250px"}
    html.Br(),
        

    
    html.Br(), 
    
    
    dbc.Row([
          dbc.Col([
            html.H3('Sale ID'
                    ,style={'font-size': '25px'}
                    ),

              
              ], width=3, md=4),
          
          dbc.Col([          
              dcc.Dropdown(id='saleid_dd', value='',
                          searchable = True, search_value='',
                          placeholder= 'Please select ...',
                          clearable=True,
                          persistence = True,
                          persistence_type = 'memory',
                          # multi = True
                          ),
              ])
          ]),
    
    
    dbc.Row([
        dbc.Col([
            html.P("Listing",
                    style={"textDecoration":"underline"}),
            
         
            dash_table.DataTable(id='table', 
                                    columns=[
                                        {'name': 'Customer', "id": 'Customer'},
                                        {'name': 'Name', "id": 'Name'},
                                        {'name': Sale_ID', "id": 'Saleid'},  
                                        {'name': 'Amount', 'id':Amountt'},
                                        {'name': 'Date', 'id':'Date'},
                                        {'name': 'View', 'id':'view', 'type':'text', 'presentation':'markdown'},
 
                                        
                                        ],
                                  style_cell={'textAlign': 'left'},
                                  # markdown_options = {'link_target': '_self'}
                                  
                                  ),
           
                ]),
            ]),   
        html.Br(),
        dcc.Store(id= 'store'),

    ],
    # fluid = True
    
    
    )      



@callback(
    Output('date_dd','options'),
    # Output('store','data'),
    Input('product_dd', 'value')
    )


def update_dd (product_dd):
  
    date = df.drop_duplicates(['Date'], inplace= False)
    
    relevant_date = date[ df['Product'] == product_dd]['Date'].values.tolist()

    date_option= [dict(label=x,value=x)for x in relevant_date]
    
    
    return date_option




@callback(
    Output('saleid_dd','options'),
    Input('date_dd', 'value'),
    # Input('store', 'data'),
    )


def update_dd (date_dd):
          
    id= df.drop_duplicates(['Sale_ID'], inplace= False)
    
    relevant_id= id[ df['Date'] == date_dd]['Sale_ID'].values.tolist()
    
    id_option= [dict(label=x,value=x)for x in relevant_id]

   
    return id_option
    


@callback(
    Output('store','data'),
    Input('saleid_dd', 'value'),

    )


def get_data (id):
    
    return id    
        


# #TABLE

@callback(
    Output('table', 'data'),
    Input('store', 'data'),


    )

def update_table(selection):
    if len (selection) == 0:
        return dash.no_update
    
    else:  

        dff = df[(df['Sale_ID'] == selection)] 
               
        equit = dff['Sale_ID'].to_list()       

        dff['view'] = [f"[View](/details/{ticker})" for ticker in equit]               
        
        
        columns = dff[['Customer', 'Name', 'Sale_ID',  'Amount', 'Date','view']]

        
        data= columns.to_dict('records')
        
        
        
        return data


page2.py

import plotly.express as px
from plotly.offline import plot

import dash
from dash import dcc, html, callback

from dash.dependencies import Output,Input, State
import dash_bootstrap_components as dbc
from dash import dash_table
from dash_table import DataTable, FormatTemplate
import dash_bootstrap_components as dbc

import pandas as pd
import pandas_datareader.data as web


from datetime import date, datetime


import pyodbc
import os
import psycopg2

from plotly.io import write_image
import flask
import base64

import json



def title(ticker=None):
    return f"{ticker} Analysis"


dash.register_page(__name__, 
                   path_template='/details/<ticker>',
                   path="/details/sale001A",
                   title = title)

# dash.register_page(__name__, path='/profile/<reference>')


    
    
# # read data from csv
dfk= pd.read_csv("dummy2.csv")


def layout(ticker= None, **other_unknown_query_strings):
  
    dfk = pd.read_csv("dummy2.csv")
    df = dfk.Sale_ID(ticker).reset_index()


    df['year1'] = pd.to_datetime(df['Date'], format = '%d/%m/%Y', errors='coerce').dt.year
    df['date1'] = pd.to_datetime(df['Date'], format = '%d/%m/%Y', errors='coerce')
    df['date2'] = pd.to_datetime(df['Date'], format = '%d/%m/%Y', errors='coerce').dt.date
    df['day1'] = pd.to_datetime(df['Date'], format = '%d/%m/%Y', errors='coerce').dt.day
    

    product_cat = list(df['Product'].unique()) 
    
    prod2 = tuple(list(df['Product'].unique()) )
      
    
    df2 = df.copy()
    df2.sort_values(by= ['Merchant ID','Product', 'Tnx Date', ], inplace = True)         
    merchant_cat = list(df2['Merchant ID'].unique()) 

    
    return dbc.Container([
              dbc.Row([
            dbc.Col([
                html.P(f"Profile: {ticker}",
                        style={"textDecoration":"underline"}),

                       
                dash_table.DataTable(id='tableprofile', 
                                        columns=[
                                            {'name': '', "id": 'header'},
                                            {'name': 'Information', "id": 'info'},
    
                                                ],  
                                     
                                      style_cell={'textAlign': 'left'},
                                     
                                      style_cell_conditional=[
                                                                  {'if': {'column_id': 'header'},
                                                                  'width': '150px'},
                                                                
                                                                  {'if': {'column_id': 'info'},
                                                                  'width': '300px'},
                                                                
                                                                
                                                                  ],
                                      # export_format='csv',
                                      ),
                html.Br(),
                
      
    
@callback(
    Output('tableprofile', 'data'), 
    Input('store', 'data')

    )


            

def update_table(selection): #, store
    if len (selection) == 0:
        return dash.no_update
    
    else:
               
        dff = dfk[dfk['Sale_ID'] == selection]  
        
        transpose = dff.melt(id_vars = ['Reference_ID']
                  ,var_name = ['header']
                  ,value_name = 'info')
        
        
        info = transpose[transpose['header'].isin(['Product', 'Customer', 'Name', 'Sale ID', 'Amount'])]

        
        
        columns = info[['header','info']]


        data= columns.to_dict('records')

       
        return data


Hi,

can it do like that?

To read data from an Excel CSV file instead of using Yahoo Finance, you’ll need to use Pandas’ read_csv function instead of yf.Ticker . The Ticker method is specific to the yfinance library and does not apply to a Pandas DataFrame. Here’s how you can modify the code:

import pandas as pd

def layout(ticker=None, **other_unknown_query_strings):
    # Read data from a CSV file
    df = pd.read_csv('path_to_your_csv_file.csv')
    df["Date"] = pd.to_datetime(df["Date"])