Esempio n. 1
0
def get_stock_info(stock_symbol):

    ticker_acao = Ticker(stock_symbol)
    resultado = ticker_acao.get_modules(['financialData', 'quoteType'])

    codigo = itemgetter(stock_symbol)(resultado)
    retorno = {'result': codigo}
    return json.dumps(retorno), 200
Esempio n. 2
0
def create_stocks():

    # read ticker symbols from the text area
    StockTextarea = request.form['StockTextarea'].upper().replace(" ", "")

    """# read ticker symbols from the text area
    volume = request.form['volume']"""

    #print('Volume flag: ' + volume)

    is_error = False

    if StockTextarea.strip() == '':
        flash('Please, Enter tickers on ticker Area')
        is_error = True        

    
    symbol = StockTextarea.split(',')

    symbol_index = StockTextarea.split(',')

    symbol_index.append('NDAQ')
    symbol_index.append('^DJI')
    symbol_index.append('^GSPC')
   

    if len(symbol) > 10:
        flash('Please, Enter 10 tickers maximum')
        is_error = True


    # Get Start Date
    SD = ObtainDate(request.form['datefrom'])
     
    #Print if there is a error with the date SD
    if SD == '':
        is_error = True   
    
    # Get End Date
    ED = ObtainDate(request.form['dateto'])
    
    #Print if there is a error with the date ED
    if ED == '':
        is_error = True

   # Get Current Date
    TD = datetime.date.today()

   #Print if there is a error with the date ED
    if SD.strftime("%Y%m%d") > TD.strftime("%Y%m%d"):
        flash('The start date can not higher than today')
        is_error = True

    #Print if there is a error with the date ED
    if ED.strftime("%Y%m%d") > TD.strftime("%Y%m%d"):
        flash('The end date can not higher than today')
        is_error = True  

    #Print if there is a error with the date ED
    if ED <  SD:
        flash('The end date can''t be less than the start date')
        is_error = True           

    # Get number of days<
    dt = (ED - SD)
    countDays = dt.days

    if countDays > 27:
        flash('The count of the days can not be greater than 27 days')
        is_error = True 
    
    if is_error:
        return redirect(url_for('Index'))
        #return redirect(url_for('Index',PstockTextarea =request.form['StockTextarea'],P_StartDate=request.form['datefrom'],P_EndDate=request.form['dateto']))

    list_yec = []

    tree_stocks = {}

    #Set tickers
    m = Ticker(symbol_index)

    #Get index prices
    list_NDAQ = []
    
    list_NDAQ.append(m.price['NDAQ']['shortName'])
    list_NDAQ.append("{:.2f}".format(m.price['NDAQ']['regularMarketPrice']))  
    list_NDAQ.append("{:.2f}".format(m.price['NDAQ']['regularMarketChange']))    
    list_NDAQ.append("{:.2f}".format(m.price['NDAQ']['regularMarketChangePercent'] * 100))   

    list_DJI = []

    list_DJI.append(m.price['^DJI']['shortName'])
    list_DJI.append("{:.2f}".format(m.price['^DJI']['regularMarketPrice'])) 
    list_DJI.append("{:.2f}".format(m.price['^DJI']['regularMarketChange']))    
    list_DJI.append("{:.2f}".format(m.price['^DJI']['regularMarketChangePercent'] * 100))   

    list_GSPC = []
    
    list_GSPC.append(m.price['^GSPC']['shortName'])
    list_GSPC.append("{:.2f}".format(m.price['^GSPC']['regularMarketPrice']))  
    list_GSPC.append("{:.2f}".format(m.price['^GSPC']['regularMarketChange']))    
    list_GSPC.append("{:.2f}".format(m.price['^GSPC']['regularMarketChangePercent'] * 100))     

    tree_stocks['NDAQ'] = list_NDAQ
    tree_stocks['DJI'] = list_DJI 
    tree_stocks['GSPC'] = list_GSPC 
    #End Index  

    list_dates = []

    for stock in symbol:
        try:
            #get prices info 
            f = web.DataReader(stock, 'yahoo', SD, ED)

            l_count_stock = len(f)
            
            list_yec = []

            try:
                #get earnig date            
                yec_date = (datetime.date.fromtimestamp(m.get_modules('calendarEvents')[stock]['earnings']['earningsDate'][0]))
                yec_count = (yec_date - TD).days

                if yec_count > 1:
                    yec_desc = str(yec_count) + ' days to earnings call'
                else:
                    if yec_count >= 0:
                        yec_desc = str(yec_count) + ' day to earnings call'
                    else:
                        yec_desc = ''
                        yec_count = ''

                list_yec.append(yec_count)
                list_yec.append(yec_desc)
            except:
                list_yec = []

            try:
                #get Name and Industry
                l_current_price = m.financial_data[stock]['currentPrice']
                current_price = "{:.2f}".format(l_current_price)
            except:
                l_current_price = 0
                current_price = ''                

            try:
                #get Name and Industry
                stock_name = m.price[stock]['longName']
                stock_industry = 'Industry: ' + m.asset_profile[stock]['industry']
            except:
                stock_name = ''
                stock_industry = ''

            #reset values
            ChangeStock = ''
            ChangeStock_percent = ''
            ChangeStock_pre = ''
            ChangeStock_percent_pre = ''
            ChangeStock_post = ''
            ChangeStock_percent_post = ''                

            try:
                #get Change
                l_change = m.price[stock]['regularMarketChange']
                ChangeStock = "{:.2f}".format(l_change)
                l_change_percent = m.price[stock]['regularMarketChangePercent']*100
                ChangeStock_percent  = "{:.2f}".format(l_change_percent)               
            except:
                ChangeStock = ''
                ChangeStock_percent = ''

            try:
                #get Change pre
                l_change_pre = m.price[stock]['preMarketChange']
                ChangeStock_pre = "{:.2f}".format(l_change_pre)
                l_change_percent_pre = m.price[stock]['preMarketChangePercent']*100
                ChangeStock_percent_pre  = "{:.2f}".format(l_change_percent_pre)              
            except:
                ChangeStock_pre = ''
                ChangeStock_percent_pre = ''

            try:
                #get Change post
                l_change_post = m.price[stock]['postMarketChange']
                ChangeStock_post = "{:.2f}".format(l_change_post)
                l_change_percent_post = m.price[stock]['postMarketChangePercent']*100
                ChangeStock_percent_post  = "{:.2f}".format(l_change_percent_post)               
            except:
                ChangeStock_post = ''
                ChangeStock_percent_post = ''                                

                     

            date_index = l_count_stock

            #count dates
            if date_index > 0:
                date_index = date_index - 1
            
            tree_stock = {}    

            #Build List Dates
            if len(list_dates) == 0:
                list_dates = []    
                
                #get dates
                for i in range(l_count_stock):
                    list_dates.append(f.index[date_index - i].strftime("%Y-%m-%d"))

            #Build List Prices
            list_prices = []

            l_date_price = 0
            
            #get prices
            for i in range(l_count_stock):
                date_price = f.loc[f.index[date_index - i],'Close']
                l_date_price +=  date_price
                list_prices.append("{:.2f}".format(date_price))
                
            #get average stock    
            l_average_stock = (l_date_price/l_count_stock)
            #get difference
            l_difference = (l_average_stock - l_current_price)

            if l_current_price != 0:
                l_average_dif = (l_difference/l_current_price)*100


            #tree_stocks[stock+'0'] = info_stock.info['industry']
            #tree_stocks[stock+'1'] = info_stock.calendar.loc[info_stock.calendar.index[0],'Value'].strftime("%Y-%m-%d")
            #tree_stocks[stock+'1'] = stock
            average_list = []
            average_list.append("{:.2f}".format(l_average_stock))
            average_list.append('Average Price: ' + "{:.2f}".format(l_average_stock))
            average_list.append("{:.2f}".format(l_difference))
            average_list.append("{:.2f}".format(l_average_dif) + '%')
            average_list.append('Returning to Avg: ' + "{:.2f}".format(l_difference) + '   (' + "{:.2f}".format(l_average_dif) + '%)')
            average_list.append(ChangeStock)
            average_list.append(ChangeStock_percent)  
            average_list.append(ChangeStock_post)
            average_list.append(ChangeStock_percent_post)  
            average_list.append(ChangeStock_pre)
            average_list.append(ChangeStock_percent_pre)                          

            ChangeStock_percent_pre


            tree_stock[stock+'0'] = 'DATA_FOUND'
            tree_stock[stock+'1'] = stock_name
            tree_stock[stock+'2'] = stock_industry
            tree_stock[stock+'3'] = list_yec  
            tree_stock[stock+'4'] = current_price         
            tree_stock[stock+'5'] = average_list
            #tree_stock[stock+'7'] = list_dates
            tree_stock[stock+'6'] = list_prices   
        except:
            tree_stock = {}
            tree_stock[stock+'0'] = 'NO_DATA_FOUND'
            tree_stock[stock+'1'] = 'There is no information for the symbol'
            tree_stocks[stock] = tree_stock
            continue 

        tree_stocks[stock] = tree_stock

    
    tree_stocks['DATES'] = list_dates 
  

    return render_template('create_stocks.html', pTreeStocks=tree_stocks)    
#tickers.income_statement(frequency="q")

#See list of allowable modules
#aapl = Ticker('aapl')
#All modules will get data for all the modules
#aapl.all_modules

#You can get multiple modules in the same call
#https://github.com/dpguthrie/yahooquery/blob/master/README.md#accessing-multiple-modules
modules = [
    'cashflowStatementHistory', 'cashflowStatementHistoryQuarterly',
    'balanceSheetHistory', 'balanceSheetHistoryQuarterly',
    'incomeStatementHistory', 'incomeStatementHistoryQuarterly'
]

financial_statement_data = tickers.get_modules(modules)

cash_flow_annual_list = []
balance_sheet_annual_list = []
income_statement_annual_list = []

cash_flow_quarterly_list = []
balance_sheet_quarterly_list = []
income_statement_quarterly_list = []

cash_flow_annual_column_name_list = []
balance_sheet_annual_column_name_list = []
income_statement_annual_column_name_list = []

cash_flow_quarterly_column_name_list = []
balance_sheet_quarterly_column_name_list = []
Esempio n. 4
0
def get_financials(exchange='SGX', delimiter='.SI'):
    '''
    Query stock financials (quarterly and annual).    
    Parameter:
        exchange      : Short name for stock exchange. Default value is SGX
        delimiter     : RIC code accompanying tickers
    '''
    # Initialise parameters #
    ## Tickers ##
    filepath = re.split(exchange, download_path)[0]
    stocks = pd.read_excel(filepath + exchange + '_TICKERS.xlsx')
    target_tickers = list(stocks['TICKER'])
    ## Modules ##
    modules = [
        'balanceSheetHistory', 'balanceSheetHistoryQuarterly',
        'incomeStatementHistory', 'incomeStatementHistoryQuarterly',
        'cashflowStatementHistory', 'cashflowStatementHistoryQuarterly',
        'defaultKeyStatistics'
    ]
    ## Errata tickers ##
    errata = []
    ## Empty DataFrames ##
    bal_sheet = pd.DataFrame([{'symbol': np.nan, 'periodType': np.nan}])
    inc_statement = pd.DataFrame([{'symbol': np.nan, 'periodType': np.nan}])
    cf_statement = pd.DataFrame([{'symbol': np.nan, 'periodType': np.nan}])
    fin_ratios = pd.DataFrame([{'symbol': np.nan}])

    # Get stock fundamnetals - Balance Sheet, Income Statement, Cash Flow #
    while True:
        if errata:
            target_tickers = [
                target_ticker for target_ticker in target_tickers
                if target_ticker not in errata
            ]
        tickers = Ticker(target_tickers)
        try:
            data = tickers.get_modules(modules)
        except Exception as e:
            ## Get errata tickers ##
            errata.append(
                re.split('/',
                         re.split(r'\%s' % delimiter, str(e))[0])[-1] +
                delimiter)
            print(errata)
        else:
            ## Retrieve working data for errata_tickers ##
            print('--Commence processing DataFrames--')
            if errata:
                for ticker in errata:
                    errata_ticker = Ticker(ticker)
                    for module in modules:
                        try:
                            errata_data = errata_ticker.get_modules(module)
                        except:
                            pass
                        else:
                            ## Combine dictionaries ##
                            for key, value in errata_data.items():
                                data.update({key: value})
                ## Merge tickers ##
                target_tickers += errata

            ## Convert dictionaries into DataFrames ##
            for target_ticker in target_tickers:
                for module in modules:
                    ### Balance Sheet ###
                    if re.search('balanceSheetHistory', module):
                        try:
                            bal_sheet = pd.concat([
                                bal_sheet,
                                pd.DataFrame(data[target_ticker][module]
                                             ['balanceSheetStatements'])
                            ],
                                                  axis=0)
                        except:
                            pass
                        else:
                            bal_sheet = get_period_type(
                                bal_sheet, target_ticker, module)
                    ### Income Statement ###
                    elif re.search('incomeStatementHistory', module):
                        try:
                            inc_statement = pd.concat([
                                inc_statement,
                                pd.DataFrame(data[target_ticker][module]
                                             ['incomeStatementHistory'])
                            ],
                                                      axis=0)
                        except:
                            pass
                        else:
                            inc_statement = get_period_type(
                                inc_statement, target_ticker, module)
                    ### Cash Flow Statement ###
                    elif re.search('cashflowStatementHistory', module):
                        try:
                            cf_statement = pd.concat([
                                cf_statement,
                                pd.DataFrame(data[target_ticker][module]
                                             ['cashflowStatements'])
                            ],
                                                     axis=0)
                        except:
                            pass
                        else:
                            cf_statement = get_period_type(
                                cf_statement, target_ticker, module)
                    ### Financial Ratios ###
                    else:
                        try:
                            fin_ratios = pd.concat([
                                fin_ratios,
                                pd.DataFrame([data[target_ticker][module]])
                            ],
                                                   axis=0)
                        except:
                            pass
                        else:
                            fin_ratios.loc[fin_ratios['symbol'].isnull(),
                                           'symbol'] = target_ticker

            ## Drop the first row ##
            bal_sheet.index = range(0, len(bal_sheet))
            bal_sheet = bal_sheet.iloc[1:]
            inc_statement.index = range(0, len(inc_statement))
            inc_statement = inc_statement.iloc[1:]
            cf_statement.index = range(0, len(cf_statement))
            cf_statement = cf_statement.iloc[1:]
            fin_ratios.index = range(0, len(fin_ratios))
            fin_ratios = fin_ratios.iloc[1:]

            ## Download DataFrames ##
            writer = pd.ExcelWriter(download_path + '\\' + exchange +
                                    r'\FIN_STATEMENTS.xlsx',
                                    engine='xlsxwriter')
            bal_sheet.to_excel(writer, sheet_name='BS', index=False)
            inc_statement.to_excel(writer, sheet_name='IS', index=False)
            cf_statement.to_excel(writer, sheet_name='CFS', index=False)
            fin_ratios.to_excel(writer, sheet_name='RATIOS', index=False)
            writer.save()
            print('--Complete processing--')

            ## Break out of while loop ##
            break

    return data, bal_sheet, inc_statement, cf_statement, fin_ratios