Flask+Echarts+sqlite搭建股票實(shí)時(shí)行情監(jiān)控

從小白出發(fā)帶你領(lǐng)略Python爬蟲(chóng)之美,關(guān)注微信公眾號(hào):機(jī)智出品(jizhjchupin),免費(fèi)獲取源代碼及實(shí)戰(zhàn)教程

一、系統(tǒng)環(huán)境:

Windows7+Python3.6+Echart3

二、結(jié)果展示:

股票實(shí)時(shí)行情.gif

三、實(shí)現(xiàn)過(guò)程:

PART ONE:tushare數(shù)據(jù)獲取sqlite存儲(chǔ)[monitor.py]

step 1:需要的庫(kù)
from sqlalchemy import create_engine
import tushare as ts
import time
import pandas as pd
step2:獲取行情并存儲(chǔ)

這里我們使用的是Tushare隔3S獲取一次股票實(shí)時(shí)行情數(shù)據(jù),并存儲(chǔ)至sqlite。

def stoc(i):
    df = ts.get_realtime_quotes('600031') 
    data=[i]
    s1 = pd.Series(data, index=range(0,1,1))
    df['id'] = s1
    engine = create_engine('sqlite:///test.db', convert_unicode=True)
    #追加數(shù)據(jù)到現(xiàn)有表
    df.to_sql('tick_data',engine,if_exists='append')

i=0
while True:
    stoc(i)
    time.sleep(3)
    i=i+1
    print('insert %s datas'%i)

PART TWO:路由器[app.py]

step 1:需要的庫(kù)
import sqlite3
from flask import *
import os
step 2:設(shè)置
app = Flask(__name__)
app.config['USERNAME']='finance'#賬號(hào)密碼
app.config['PASSWORD']='finance'
app.secret_key=os.urandom(24)
step 3:URL
@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != app.config['USERNAME']:
            error = 'Invalid username'
        elif request.form['password'] != app.config['PASSWORD']:
            error = 'Invalid password'
        else:
            session['logged_in'] = True
            flash('You were logged in')
            return redirect(url_for('index'))
    return render_template('login.html', error=error)

@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    flash('You were logged out')
    return redirect(url_for('login'))

def get_db():
    db = sqlite3.connect('test.db')
    db.row_factory = sqlite3.Row
    return db

def query_db(query, one=False):#, args=()
    db = get_db()
    cur = db.execute(query)#, args
    db.commit()
    rv = cur.fetchall()
    db.close()
    return (rv[0] if rv else None) if one else rv

@app.route("/", methods=["GET"])
def index():
    if session.get('logged_in'):
        return render_template("index.html")
    else:
        return redirect(url_for('login'))
    
@app.route("/finance", methods=["POST"])
def finance():
    if request.method == "POST":
        res = query_db("SELECT * FROM tick_data ") 
        print(int(request.form['id']))
    return jsonify(time = [x[32] for x in res],
                   price = [x[4] for x in res]) # 返回json格式

if __name__ == "__main__":
    app.run(debug=True)

PART THREE:頁(yè)面[index.html]

<!DOCTYPE html>
<html style="height: 100%" lang="en">
<head>
    <meta charset="utf-8">
    <title>My Finance</title>
    <script src="{{ url_for('static', filename='jquery-3.1.1.js') }}"></script>
    <script src="{{ url_for('static', filename='echarts.js') }}"></script>
    <!-- 引入 vintage 主題 -->
    <script src="{{ url_for('static', filename='dark.js') }}"></script>
</head>
<body style="height: 100%; margin: 0">
    <div id="main" style="height: 100%"></div>
    <script type="text/javascript">
    var myChart = echarts.init(document.getElementById('main'), 'dark');
    myChart.setOption({
        title: {
            top: 5,
            left: 'center',
            text: 'My Finance',
            textStyle: {
            color: '#00FFFF',
            fontSize: 18
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
            animation: false,
            type: 'cross',
            lineStyle: {
                color: '#376df4',
                width: 2,
                opacity: 1
                }
            }
        },
        legend: {
            top: 30,
            left: 'center',
            data:['price']
        },
        toolbox: {
        show : true,
        orient : 'vertical',
        top : '35%',
        right : 45,
        feature : {
            mark : {show: true},
            dataView : {show: true, readOnly: false},
            magicType : {show: true, type: ['line', 'bar']},
            restore : {show: true},
            saveAsImage : {show: true}
            }
        },
        xAxis: {
            data: [],
            axisLine: { lineStyle: { color: '#8392A5' } }
        },
        yAxis: {
        //maxInterval: 0.1
        //interval:0.1,
        min:'dataMin',
        axisLine: { lineStyle: { color: '#8392A5' } }
        //max:'dataMax'
        //splitNumber:5
        },
        dataZoom: [
            {
                "show": true,
                textStyle: {
                color: '#8392A5'
                },
                "type": "slider",
                handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                handleSize: '80%',
                dataBackground: {
                    areaStyle: {
                    color: '#8392A5'
                    },
                    lineStyle: {
                    opacity: 0.8,
                    color: '#8392A5'
                    }
                },
                handleStyle: {
                    color: '#fff',
                    shadowBlur: 3,
                    shadowColor: 'rgba(0, 0, 0, 0.6)',
                    shadowOffsetX: 2,
                    shadowOffsetY: 2
                },
                "start": 50,
                "end": 100,
                "orient": "horizontal"
            }
        ],
        series: [{
            name: 'price',
            type: 'line',
            //smooth:true,
            sampling:'average',
            areaStyle: {
                normal: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: 'rgba(0, 136, 212, 0.3)'
                    }, {
                        offset: 0.8,
                        color: 'rgba(0, 136, 212, 0.1)'
                    },{
                        offset: 1,
                        color: 'rgba(0, 136, 212, 0)'
                    }], false),
                    shadowColor: 'rgba(0, 0, 0, 0.1)',
                    shadowBlur: 10
                }
            },
            itemStyle: {
                normal: {
                    color: 'rgb(0,136,212)',
                    borderColor: 'rgba(0,136,212,0.2)',
                    borderWidth: 12
                }
            },
            data: []
        }]
    });
    var time = [],
        price = [],
        lastID = 0; 
    //準(zhǔn)備好統(tǒng)一的 callback 函數(shù)
    var update_mychart = function (data) { //data是json格式的response對(duì)象 
        myChart.hideLoading(); // 隱藏加載動(dòng)畫(huà)
        dataLength = data.time.length; 
        if (dataLength == lastID){clearInterval(timeTicket);};//取得數(shù)據(jù)和上次長(zhǎng)度一樣停止ajax
        lastID = dataLength; 
        time = time.slice(dataLength).concat(data.time); 
        price = price.slice(dataLength).concat(data.price.map(parseFloat)); 
        // 填入數(shù)據(jù)
        myChart.setOption({
            xAxis: {
                data: time
            },
            series: [{
                name: 'price', 
                data: price
            }]
        })
    }
    myChart.showLoading(); // 首次顯示加載動(dòng)畫(huà)
    $.get('/finance').done(update_mychart);
    var timeTicket = setInterval(function () {
        $.post('/finance',{id: lastID}).done(update_mychart);
    }, 3000);
    </script>
</body>
</html>

先運(yùn)行monitor.py獲取一些數(shù)據(jù),再運(yùn)行app.py,然后打開(kāi)http://127.0.0.1:5000,就可以看到如下界面:

Login.PNG
My Finance.PNG

源代碼鏈接:http://pan.baidu.com/s/1eSw53we
關(guān)注微信公眾號(hào)“機(jī)智出品”,回復(fù)0825,獲取密碼

機(jī)智出品.jpg
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 22年12月更新:個(gè)人網(wǎng)站關(guān)停,如果仍舊對(duì)舊教程有興趣參考 Github 的markdown內(nèi)容[https://...
    tangyefei閱讀 35,390評(píng)論 22 257
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,828評(píng)論 25 709
  • 很長(zhǎng)時(shí)間沒(méi)有登錄372165xxx了,莫名的想念,按照Q里的好友分類(lèi),一個(gè)一個(gè)的點(diǎn)開(kāi)QQ空間,我想我能了解的你們的...
    左寶右貝閱讀 237評(píng)論 0 0
  • 人就是以類(lèi)聚的,和一些人在一起開(kāi)心,和一些人在一起壓抑。到底是應(yīng)該隨性而活,還是不得不活。 說(shuō)完自己都覺(jué)得矯情。哈哈
    學(xué)著開(kāi)始閱讀 263評(píng)論 0 0
  • 我就是強(qiáng)制(員工使用格力手機(jī))又怎么樣?你是我的員工為什么不用格力手機(jī)?你對(duì)自己的產(chǎn)品都沒(méi)有信心,憑什么讓市場(chǎng)認(rèn)可...
    龜步也能行千里閱讀 398評(píng)論 3 3

友情鏈接更多精彩內(nèi)容