美文网首页
使用Altair绘制市值图

使用Altair绘制市值图

作者: 发条蛙 | 来源:发表于2017-11-08 10:37 被阅读0次

    以网易股票的股价为输入,尝试使用Altair绘制市值图:

    #!/usr/bin/env python3
    import os
    import json
    import requests
    import altair as alt
    
    stocks_file = 'stock.json'
    
    
    def fetch_stocks():
        url = 'http://quotes.money.163.com/hs/service/diyrank.php'
        fields = [
                'NO',
                'SYMBOL',
                'NAME',
                'PRICE',
                'PERCENT',
                'UPDOWN',
                'FIVE_MINUTE',
                'OPEN',
                'YESTCLOSE',
                'HIGH',
                'LOW',
                'VOLUME',
                'TURNOVER',
                'HS',
                'LB',
                'WB',
                'ZF',
                'PE',
                'MCAP',
                'TCAP',
                'MFSUM',
                'MFRATIO.MFRATIO2',
                'MFRATIO.MFRATIO10',
                'SNAME',
                'CODE',
                'ANNOUNMT',
                'UVSNEWS'
                ]
        payload = {
                'query': 'STYPE:EQA',
                'fields': ','.join(fields),
                'count': 0
                }
    
        response = requests.get(url, params=payload)
        if response.status_code != requests.codes.ok:
            print(response.reason)
            return False
        else:
            return response.json()
    
    
    def is_stored():
        return os.path.exists(stocks_file) and os.path.isfile(stocks_file)
    
    
    def store_stocks():
        stocks = fetch_stocks()
        if not stocks:
            return
    
        with open(stocks_file, 'w') as f:
            json.dump(stocks, f, ensure_ascii=False, indent=2)
    
    
    def read_stocks():
        if not is_stored():
            store_stocks()
    
        with open(stocks_file) as f:
            return json.load(f)['list']
    
    
    def plot():
        stocks = alt.Data(values=sorted(read_stocks(),
                                        key=lambda k: -k['TCAP'])[:30])
        chart = alt.Chart(stocks).mark_bar().encode(
                x=alt.X('TCAP:Q'),
                y=alt.Y('NAME:N', sort=alt.SortField(field='TCAP',
                        order='descending', op='sum'),
                        scale=alt.Scale(bandSize=13.0,)),
                )
        chart.serve('0.0.0.0', 8888)
    
    
    if __name__ == '__main__':
        plot()
    

    最终生成市值Top30图片如下:


    市值Top30

    最终生成的是静态图,无法互动,还是不如D3.js生成的图标漂亮。

    相关文章

      网友评论

          本文标题:使用Altair绘制市值图

          本文链接:https://www.haomeiwen.com/subject/apjemxtx.html