Get live data of nse stocks of all symbols in python/Django

Viewed 4001

I m working on a stock prediction project. This is how I want:

To show all the stocks available in Nifty50, Nifty100 or so and then the user will select the stock to predict the high and low price of a stock on next day only.

I m using Django.

What I have done till now: I m able to display a list of stock.

def index(request):
    api_key = 'myAPI_Key'

    url50 = 'https://archives.nseindia.com/content/indices/ind_nifty50list.csv'
    url100 = 'https://archives.nseindia.com/content/indices/ind_nifty100list.csv'
    url200 = 'https://archives.nseindia.com/content/indices/ind_nifty200list.csv'

    sfifty = requests.get(url50).content
    shundred = requests.get(url100).content
    stwohundred = requests.get(url200).content

    nifty50 = pd.read_csv(io.StringIO(sfifty.decode('utf-8')))
    nifty100 = pd.read_csv(io.StringIO(shundred.decode('utf-8')))
    nifty200 = pd.read_csv(io.StringIO(stwohundred.decode('utf-8')))

    nifty50 = nifty50['Symbol']
    nifty100 = nifty100['Symbol']
    nifty200 = nifty200['Symbol']



    context = {
        'fifty': nifty50,
        'hundred': nifty100,
        'twohundred': nifty200
               }

    return render(request, 'StockPrediction/index.html', context)

What I want: I want to get the live data of all stocks open, high,LTP,Change, Volume.by mean of live data is that it will change as per stock values will change.

Please Help!

1 Answers

You must combine Ajax/Jquery like code below to periodically get data and update values in DOM :

(function getStocks() {
    $.ajax({
            type: "GET",
            url: "url to your view",
            success: function (data) {
                // here you can get data from backend and do changes like
                // changing color by the data coming from your view.
            }
        }).then(function() {           // on completion, restart
       setTimeout(getStocks, 30000);  // function refers to itself
    });
})();

But be careful about making too requests, you must choose proper interval right in this line setTimeout(getStocks, "proper interval");

And in your view you should put queries into a JSON format something like this :

return JsonResponse({'stocks': stocks})

here stocks must be in json format.

Related