django and echarts used for data visualization to analyze funds that rose by top 5 in the week

Start

This paper studies a fund crawler of Tiantian fund network

Hang the crawler on the server the night before

Crawled the data of 1000 of 3712 mixed funds among more than 8000 funds

And save it to the database

1000 data, and some indicators have been calculated, such as the rose proportion

The formula is

Monthly / quarterly increase

There is also the corresponding situation of roses, which can be judged according to the rose ratio calculated by us

    if i >= 0.8:
        w.append('Rapid rise')
    elif 0.8 > i >= 0.5:
        w.append('rise')
    elif 0.5 > i >= 0.2:
        w.append('Flat')
    elif 0.2 > i >= 0:
        w.append('slide downward')
    else:
        w.append('Reversal of the situation')

These data are available, and then I want to show it without django?

Just do it

01

Start preparing

I've heard that echarts can do visualization before, but I've never used it or learned it

I had a brain fever yesterday. I went directly to the official website to see the demo and documents

It's not difficult to copy the js file directly and then copy the demo

Modify as you want

This is the demo of the official website

Copy the code directly

Then read it and change it roughly

The style is not difficult to change. The most difficult thing is the color matching. The color on the official website is OK, because it is top 5

So there are five pieces of data

You need five colors

It's really hard for me-=-

Change the style and read the code, and this part of the task is completed

02

Back end preparation

There is no doubt that we use django at the back end

However, because we need the cooperation of echarts, we choose the back-end query database

Then return to json

This is also convenient for front-end loading

This uses jquery

I've used jquery before, but it's the first time if I write it myself

After many studies, I finally decided to write with a very simple example

$(document).ready(function(){
    $("button").click(function(){
        $.getJSON("demo_ajax_json.js",function(result){
            $.each(result, function(i, field){
                $("div").append(field + " ");
            });
        });
    });
});

This is read through the js file

We get it directly through our ur here

So, start our django first and write a simple view that returns json

def testDB(request):
    conn=pymysql.connect(host="127.0.0.1",user="root",password="password",port=3306,database="fiance")
    cursor=conn.cursor()
    sql="""
        SELECT * from sheet1 order by Nearly 1 week DESC LIMIT 5"""
    cursor.execute(sql)
    result=cursor.fetchall()
    return HttpResponse(json.dumps(result), content_type="application/json")

Then configure our url

from django.urls import path
from .views import index,testDB,displayJson
app_name="article"
urlpatterns = [
    ···
    path('DB/',testDB),
    ···
]

At this time, let's start django to test

Can I return

Open the browser and enter the url we have configured

You can see that we have successfully returned json data

And it is also the first five data

Then let's go straight to work

Start writing front-end pages

03

Get up

First, simply write a return page in views

def displayJson(request):
    return render(request,"display.html")

Then configure the url

from django.urls import path
from .views import index,testDB,displayJson

app_name="article"
urlpatterns = [
    ···
    ···
    path('json/',displayJson)
]

The next step is to configure our front-end page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="//www.jb51.net/jslib/jquery/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.staticfile.org/echarts/4.7.0/echarts.min.js"></script>
</head>
<body>
<h3 style="text-align: center">Weekly increase top5 Hybrid fund</h3>
 <div id="main" style="width:1300px;height:900px;margin: 0 auto;"></div>

</body>
</html>

This is the skeleton. Build it first

One of the small problems is that our rose proportion calculates a very long float

That means there are many decimals

So when displayed

It's a long time, image visual experience

So we write a forensics function

Then return a two digit decimal

function keepTwoDecimal(num) {
               var result = parseFloat(num);
               if (isNaN(result)) {
                   alert('Error passing parameter, please check!');
                  return false;
              }
               result = Math.round(num * 100) / 100;
               return result;
};

Then write the script

<script>

   
var app = {};

var chartDom = document.getElementById('main');
var myChart = echarts.init(chartDom);
var option;

var posList = [
    'left', 'right', 'top', 'bottom',
    'inside',
    'insideTop', 'insideLeft', 'insideRight', 'insideBottom',
    'insideTopLeft', 'insideTopRight', 'insideBottomLeft', 'insideBottomRight'
];

app.configParameters = {
    rotate: {
        min: -90,
        max: 90
    },
    align: {
        options: {
            left: 'left',
            center: 'center',
            right: 'right'
        }
    },
    verticalAlign: {
        options: {
            top: 'top',
            middle: 'middle',
            bottom: 'bottom'
        }
    },
    position: {
        options: posList.reduce(function (map, pos) {
            map[pos] = pos;
            return map;
        }, {})
    },
    distance: {
        min: 0,
        max: 100
    }
};

app.config = {
    rotate: 90,
    align: 'center',
    verticalAlign: 'middle',
    position: 'insideBottom',
    distance: 15,
    onChange: function () {
        var labelOption = {
            normal: {
                rotate: app.config.rotate,
                align: app.config.align,
                verticalAlign: app.config.verticalAlign,
                position: app.config.position,
                distance: app.config.distance
            }
        };
        myChart.setOption({
            series: [{
                label: labelOption
            }, {
                label: labelOption
            }, {
                label: labelOption
            }, {
                label: labelOption
            },{
                label: labelOption
            },
            ]
        });
    }
};

var labelOption = {
    show: true,
    position: app.config.position,
    distance: app.config.distance,
    align: app.config.align,
    verticalAlign: app.config.verticalAlign,
    rotate: app.config.rotate,
    formatter: '',
    fontSize: 18,
    rich: {
        name: {
        }
    }
};

$.getJSON('/blog/DB',function (datas) {
    var names=new Array();
    var as=new Array();
    var a=null;
    var colors=['#F2385A','#F5A503','#E9F1DF','#4AD9D9','#36B1BF']
    for(let u=0;u<datas.length;u++){
        var stra=datas[u][1]+"~"+datas[u][2];
        names[u]=stra;
        a={
                name: names[u],
                itemStyle:{
                    normal:{
                        label:{
                            show:true,
                            posList:"top",
                        },
                        color:colors[u],
                    }
                },
                type: 'bar',
                barWidth:30,
                barGap: 0,
                label: labelOption,
                emphasis: {
                    focus: 'series'
                },
                data: [datas[u][4], datas[u][5], keepTwoDecimal(datas[u][7]), datas[u][10], datas[u][11]]
            };
        as[u]=a;
    }

    option = {
        color:['#15F995','#D9E39D','#7C80FE','#FFFF28','#830E45'],
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: names
        },
        toolbox: {
            show: true,
            orient: 'vertical',
            left: 'right',
            top: 'center',
            feature: {
                mark: {show: true},
                dataView: {show: true, readOnly: false},
                magicType: {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                restore: {show: true},
                saveAsImage: {show: true}
            }
        },
        xAxis: [
            {
                type: 'category',
                axisTick: {show: false},
                data: ['Increase in recent week%', 'Increase in recent January%', 'Rose proportion', 'Increase in recent quarter%', 'Increase in recent two quarters%']
            }
        ],
        yAxis: [
            {
                type: 'value'
            }
        ],
        series:as,
    };
    option && myChart.setOption(option);
})
</script>

Run successfully

04

Ending

Several walls were encountered this time:

  1. The color matching of each histogram, including setting the color of each.

2. How to get top5 from the database? The solution is to sort first and then use limit

3. The rest are some configured pits in echarts, which can be solved from Baidu

In summary, if a rookie doesn't give up, he will become a big man sooner or later

Posted by cape on Fri, 15 Apr 2022 17:47:43 +0930