Tuesday, 31 December 2019

django mpld3 live stock plot

server starts

1 minute elapsed

5 minute passed

#power shell

pip install yahoo-fin
pip install requests_html

------------------------------------
#django/app/view

from django.shortcuts import render
import matplotlib.pyplot as plt
from mpld3 import plugins, fig_to_html, save_html, fig_to_dict
import json
import numpy as np
from datetime import datetime
from yahoo_fin import stock_info as si

class NumpyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)

x, y = [], []

def index(request):
    fig1, ax1 = plt.subplots()
    global x, y

    x.append(datetime.now())
    price = si.get_live_price('aapl')
    y.append(price)

    if len(x) < 2:
        return render(request, 'mpld/index.html')

    ax1.plot(x, y)
    ax1.grid(color='lightgray', alpha=0.7)
    ax1.set_xlabel('time', fontsize=15)
    ax1.set_ylabel('price', fontsize=15)
    ax1.set_title('Live Apple stock Price', fontsize=20)

    g1 = json.dumps(fig_to_dict(fig1), cls=NumpyEncoder)

    return render(request, 'mpld/index.html',
                  {'graph1': g1})

-----------------------------------
#django/template/index

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <!--refresh page every second-->
    <meta http-equiv="refresh" content="1" />
    <title>MPLD3</title>
    <!--bootstrap-->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</head>
<body>
    <script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
    <script type="text/javascript" src="http://mpld3.github.io/js/mpld3.v0.2.js"></script>
    <div class="row">
        <div class="col">
            <div id="fig1">graph1</div>
        </div>
    </div>

    <script type="text/javascript">
        mpld3.draw_figure("fig1", {{graph1 | safe}});
</script>
</body>
</html>

reference:
https://stackoverflow.com/questions/441147/how-to-subtract-a-day-from-a-date
http://theautomatic.net/2018/07/31/how-to-get-live-stock-prices-with-python/
http://chuanshuoge2.blogspot.com/2019/12/django-mpld3-multiple-plots-on-html-page.html

auto refresh page
https://stackoverflow.com/questions/2787679/how-to-reload-page-every-5-seconds

yahoo_fin
http://theautomatic.net/yahoo_fin-documentation/

No comments:

Post a Comment