YFinance Flask Web App Doesn't Display Non-US Market Prices

78 Views Asked by At

I'm trying to display stock prices and other financial metrics with yfinance. It is only working for US market stocks. When I check the network, it seems that non-US market results are coming through, but they are not being displayed. I suppose there is a data formatting issue. Can you help me?"

non-us stock ticker code result is coming as you can see but not displaying

flask code python

import yfinance as yf
from flask import request, render_template, jsonify, Flask 


app = Flask(__name__, template_folder='templates')


@app.route('/')
def index():
    return render_template('index.html')

@app.route('/get_stock_data', methods=['POST'])
def get_stock_data():
    ticker = request.get_json()['ticker']
    data = yf.Ticker(ticker).history(period='1y')
    if data.empty:
        return jsonify({"error": "No data found for the given ticker."})
    return jsonify({"currentPrice": data.iloc[-1].Close,
                     'openPrice': data.iloc[-1].Open})
    
    
    
if __name__ == '__main__':
    app.run(debug=True)
    

js code

var tickers = JSON.parse(localStorage.getItem('tickers')) || [];
var lastPrices = {};
var counter = 10;

function startUpdateCycle() {
    updatePrices(); 
    setInterval(function() {
        counter--;
        $('#counter').text(counter);
        if (counter <= 0) {
            updatePrices();
            counter = 10;
        }
    }, 1000);
}

$(document).ready(function() {
    tickers.forEach(function(ticker) {
        addTickerToGrid(ticker);
    });
$('#tickers').on('click', '.remove-btn', function() {
    var tickerToRemove = $(this).data('ticker');
    tickers = tickers.filter(t => t !== tickerToRemove);
    localStorage.setItem('tickers', JSON.stringify(tickers));
    $('#'+tickerToRemove).remove();
});
    updatePrices();

    $('#add-ticker-form').submit(function(e) {
        e.preventDefault();
        var newTicker = $('#new-ticker').val().toUpperCase();
        if (!tickers.includes(newTicker)) {
            tickers.push(newTicker);
            localStorage.setItem('tickers', JSON.stringify(tickers))
            addTickerToGrid(newTicker);
        }
        $('new-ticker').val('');
        updatePrices();
    });

    $('#tickers-grid').on('click', '.remove-btn', function() {
        var tickerToRemove = $(this).data('ticker');
        tickers = tickers.filter(t => t !== tickerToRemove);
        localStorage.setItem('tickers', JSON.stringify(tickers));
        $('#'+tickerToRemove).remove();
    });
  
    startUpdateCycle();
});

function addTickerToGrid(ticker) {
    $('#tickers-grid').append(`<div id="${ticker}" class="stock-box"><h2>${ticker}</h2><p id="${ticker}-price"></p><p id="${ticker}-pct"></p><button class="remove-btn" data-ticker="${ticker}">Remove</button></div>`);
}

function updatePrices() {
    tickers.forEach(function(ticker) {
        $.ajax({
            url: '/get_stock_data',
            type : 'POST',
            data: JSON.stringify({ticker: ticker}),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (data) {
                var changePercent = ((data.currentPrice - data.openPrice) / data.openPrice) * 100;
                var colorClass;
                if (changePercent <= -2) {
                    colorClass = 'dark-red'
                } else if (changePercent <= 0) {
                    colorClass = 'red'
                } else if (changePercent == 0) {
                    colorClass = 'gray'
                }
                else if (changePercent <= 2) {
                    colorClass = 'green'
                }
                else {
                    colorClass = 'dark-green'
                }
                $('#'+ticker+'-price').text('$'+data.currentPrice.toFixed(2));
                $('#'+ticker+'-pct').text(changePercent.toFixed(2)+'%');
                $('#'+ticker+'-price').removeClass("dark-red red gray green dark-green").addClass(colorClass);
                $('#'+ticker+'-pct').removeClass("dark-red red gray green dark-green").addClass(colorClass);

                var flashClass;
                if (lastPrices[ticker] > data.currentPrice) {
                    flashClass = 'red-flash';
                } else if (lastPrices[ticker] < data.currentPrice) {
                    flashClass = 'green-flash';
                } else {
                    flashClass = 'gray-flash';
                }
                lastPrices[ticker] = data.currentPrice;

                $('#'+ticker).addClass(flashClass);
                setTimeout(function() {
                    $('#'+ticker).removeClass(flashClass);
                },  1000);
            }
        });
    });
}
0

There are 0 best solutions below