python商业数据分析报告范文_python自动化撰写数据分析报告

在工作中经常要出具各种报告,我们可以根据报告周期来设置定时任务自动生成数据分析报告。首先要确定报告模板,给模板中的每一个变动值赋予一个参数;然后根据业务需求再python中定义每个变动值的计算方式;最后定时任务触发后自动跑程序读取模板填充数据然后再通过接口发送给指定的接收人。这样就实现了自动化撰写及发送报告,减少繁琐的手工操作计算了

数据分析报告

报告模板

完整代码如下:

#一、安装并引入所需要的模块

import datetime

from collections import ChainMap

import matplotlib as mpl

import matplotlib.pyplot as plt

from docx.shared import Mm

from docxtpl import DocxTemplate,InlineImage

import random

import numpy as np

#二、计算填充的数据

#1.有关时间的计算,报告可能需要按周、按月、按季度来填写,首先要明确我们数据的所属期

#a.根据年份来比较:

today = datetime.date.today()

month = today.month

now_year = str(today.year)+"-01-01"

last_year = str(today.year-1)+"-01-01"

last_year2 = today-datetime.timedelta(365)

year = str(today.year)

year2 = str(last_year2.year)

#b.按照季度来计算

quarterList = []

last_year2 = today-datetime.timedelta(365)

year = str(today.year)

year2 = str(last_year2.year)

years,tails = [[year,year2],["-12-31","-09-30","-06-30","-03-31"]]

for i in years:

for j in tails:

quarterList.append(i+j)

quarterList.append(str(int(year2)-1)+"-12-31")

month1 = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]

quarter1 = [str(int(year)-1)+"-12-31",str(int(year))+"-03-31",str(int(year))+"-06-30",str(int(year))+"-09-30"]

quarter = [quarter1[i] for i in range(len(quarter1)) if month in month1[i]][0]

#c.按照每周来计算

monday,sunday = datetime.date.today(),datetime.date.today(),

one_day = datetime.timedelta(days = 1)

#返回当前的星期一和星期天的日期

while monday.weekday() !=0:

monday -=one_day

while sunday.weekday() !=0:

sunday +=one_day

#返回上周的星期一和星期天的日期

monday_W1 =monday - datetime.timedelta(days = 7)

sunday_W1 =sunday - datetime.timedelta(days = 7)

#返回上上周的星期一和星期天的日期

monday_W2 = monday_W1 -datetime.timedelta(days = 7)

sunday_W2 = monday_W1 -datetime.timedelta(days = 7)

print(monday,monday_W1,monday_W2,sunday,sunday_W1,sunday_W2)

2.清洗和计算我们所需要的数据。(生成一个列表)

list = [year,year2]+ [i for i in range(1,13)]+["增多"]

3.对数据进行可视化绘图

mpl.rcParams["font.sans-serif"] = ["SimHei"]

mpl.rcParams["axes.unicode_minus"] = False

hour = [i for i in range(0,24)]

value = np.random.randint(50,size=24)

plt.plot(hour,value,"salmon",marker = "*",ms = 10, label = "个数",color = "steelblue",alpha = 0.8)

plt.title("每小时的发布个数")

plt.xlabel("时刻")

plt.ylabel("个数")

plt.legend("right")

# plt.show()

plt.savefig("发布时间点.png")

# plt.close()

三、引用报告模板填充数据

def data_to_word():

word = ["word"+str(i) for i in range(1,16)]

values = [year,year2]+ [i for i in range(1,13)]+["增多"]

data_dic = dict(zip(word,values))

doc = DocxTemplate("报告模板.docx")

pic_dic = {

"pic1":InlineImage(doc,"发布时间点.png",width = Mm(115))

}

context = dict(ChainMap(data_dic,pic_dic))

doc.render(context)

doc.save("数据分析报告.docx")

post_message()

四、通过接口把报告发送给指定的接收人

def post_message():

data = {

}

return res.json()

if __name__ == "__main__":

data_to_word()

你可能感兴趣的:(python商业数据分析报告范文_python自动化撰写数据分析报告)