免责声明:本文由作者参考相关资料,并结合自身实践和思考独立完成,对全文内容的准确性、完整性或可靠性不作任何保证。同时,文中提及的数据仅作为举例使用,不构成推荐;文中所有观点均不构成任何投资建议。请读者仔细阅读本声明,若读者阅读此文章,默认知晓此声明。
make模块主要是数据的可视化以及word报告的制作,主要含有三个模块。
1. draw_picture
1.1 模块解释
可视化作图,并保存数据到data_deal文件目录下。
函数名称 | 功能 |
draw_index | 绘制三类指数的柱状图,并保存 |
draw_amount | 绘制成交额的折线图,并保存 |
draw_change_group | 绘制股票涨跌分布的柱状图,并保存 |
draw_tenth_stock | 绘制股票成交额前十的柱状图,并保存 |
store_picture | 运行上述所有函数 |
1.2 模块源码
'''
将数据转换为图片,便于后续插入word
'''
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as mt
import pandas as pd
from Automatic_report.data_deal.store_path import get_path
def draw_index(index_name):
# 绘制指数柱状图
file_path = get_path()
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False # 防止中文乱码的处理
base_df = pd.read_excel(file_path + index_name + '.xlsx')
name = base_df['指数名称']
day = base_df['当日涨幅']
year = base_df['当年涨幅']
x = np.arange(len(base_df))
zt = plt.figure()
p1 = zt.add_subplot(211)
p1.yaxis.set_major_formatter(mt.PercentFormatter(xmax=1, decimals=0))
p1.bar(x, day, width=0.1, label='当日涨幅')
plt.title(index_name + '指数收益情况')
for i in range(len(base_df)):
p1.text(x[i], day[i] * 1.05, format(day[i], '.2%'), va="bottom", ha="center")
plt.legend(loc='best')
p2 = zt.add_subplot(212)
p2.yaxis.set_major_formatter(mt.PercentFormatter(xmax=1, decimals=0))
p2.bar(x, year, width=0.1, label='当年涨幅')
for i in range(len(base_df)):
p2.text(x[i], year[i] * 1.05, format(year[i], '.2%'), va="bottom", ha="center")
# 设置横轴参数
plt.xticks(x, labels=name, rotation=-90)
plt.legend(loc='best')
plt.savefig(file_path + index_name + '.jpg', dpi=300, bbox_inches="tight")
def draw_amount(name):
file_path = get_path()
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False # 防止中文乱码的处理
vol_df = pd.read_excel(file_path + name + '.xlsx')
zt = plt.figure()
plt.title('沪深两市历史成交额(亿)')
plt.plot(pd.to_datetime(vol_df['日期']), vol_df['总成交额(亿)'])
plt.legend(loc='best')
plt.savefig(file_path + name + '.jpg', dpi=300, bbox_inches="tight")
def draw_change_group(name):
# 绘制股票分组的图片
file_path = get_path()
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False # 防止中文乱码的处理
change_group = pd.read_excel(file_path + name + '.xlsx')
name = change_group['涨跌幅分组']
day = change_group['数量']
x = np.arange(len(change_group))
zt = plt.figure()
p1 = zt.add_subplot(111)
plt.xticks(x, labels=name, rotation=-90)
p1.bar(x, day, width=0.1)
plt.title('股票涨跌幅分布')
for i in range(len(change_group)):
p1.text(x[i], day[i] * 1.01, day[i], va="bottom", ha="center")
plt.savefig(file_path + '涨跌幅.jpg', dpi=300, bbox_inches="tight")
def draw_tenth_stock(name):
# 成交
file_path = get_path()
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False # 防止中文乱码的处理
tenth_vol_df = pd.read_excel(file_path + name + '.xlsx').reset_index(drop=True)
name = tenth_vol_df['股票名称']
vol = tenth_vol_df['成交额(亿)']
turn = tenth_vol_df['换手率(%)']
x = np.arange(len(tenth_vol_df))
zt = plt.figure()
p1 = zt.add_subplot(211)
p1.bar(x, vol, width=0.1, label='成交额(亿)')
plt.title('成交额前十股票')
for i in range(len(tenth_vol_df)):
p1.text(x[i], vol[i] * 1.01, vol[i], va="bottom", ha="center")
plt.legend(loc='best')
p2 = zt.add_subplot(212)
p2.bar(x, turn, width=0.1, label='换手率(%)')
for i in range(len(tenth_vol_df)):
p2.text(x[i], turn[i] * 1.05, turn[i], va="bottom", ha="center")
# 设置横轴参数
plt.xticks(x, labels=name, rotation=-90)
plt.legend(loc='best')
plt.savefig(file_path + '股票前十.jpg', dpi=300, bbox_inches="tight")
def store_picture():
index_name = ['中证行业', '宽基', '风格']
for name in index_name:
draw_index(name)
draw_amount('成交额')
draw_change_group('涨跌幅分组')
draw_tenth_stock('成交前十')
print('图片生成完毕!')
if __name__ == '__main__':
store_picture()
2. word_model
2.1 模块解释
word常见功能封装成类函数,便于后续的直接调用。
函数名称 | 功能 |
set_paragraph | 插入正文标题及段落内容 |
set_table | 插入表格 |
set_picture | 插入图片 |
2.2 模块源码
'''
创建制作word常见的函数
'''
from Automatic_report.data_deal.store_path import get_path
from docx.shared import Inches
class set_word(object):
def __init__(self, doc):
self.document = doc # 接入文档
def set_paragraph(self, N, title, text):
# 创建正文N级标题及内容
t = self.document.add_heading(title, level=N)
p = self.document.add_paragraph(text)
def set_table(self, table):
# 传入DataFream表格
table_df = table.reset_index(drop=True)
row, col = len(table_df), len(table_df.columns)
table = self.document.add_table(rows=1, cols=col)
# 设置列名,第0行作为列
hdr_cells = table.rows[0].cells
for x in range(0, col):
hdr_cells[x].text = table_df.columns[x]
# 传入元素,一行一行的传入
for i in range(0, row):
row_cells = table.add_row().cells
new_col = table_df.loc[i]
for y in range(0, col):
row_cells[y].text = str(new_col[y])
def set_picture(self, name):
file_path = get_path()
# 插入图片
picture = self.document.add_picture(file_path + name + '.jpg', width=Inches(6))
3. make_report
3.1 模块解释
设置模板的格式,并添加相应的内容,然后保存word到run文件目录下。
3.2 模块源码
'''
生成word 基本模板,并保存数据
'''
from Automatic_report.make_word.word_model import *
from Automatic_report.data_deal.store_path import get_path
from docx import Document
import pandas as pd
def get_word(store_path):
# 生成报表
document = Document()
document.add_heading('股票收盘报告', 0) # 设置标题
report = set_word(document)
# 正文内容
amount_df = pd.read_excel(get_path() + '成交额.xlsx')
# 成交额
today_amount = round(amount_df['总成交额(亿)'].values[-1], 0)
yes_amount = round(amount_df['总成交额(亿)'].values[-2], 0)
amount_diff = round(today_amount - yes_amount, 0)
up_or_down = '增加约' if amount_diff >= 0 else '减少约'
amount_text = '今日沪两市成交额约为:' + str(today_amount) + '亿元,' + '较昨日' \
+ up_or_down + str(amount_diff) + '亿元。'
report.set_paragraph(1, '1.股票', amount_text + '以下是今日个股概况:')
market_df = pd.read_excel(get_path() + '市场概况.xlsx')
report.set_table(market_df)
report.set_paragraph(2, '1.1 涨跌分布', '今日股票涨跌分布如下:')
report.set_picture('涨跌幅')
report.set_paragraph(2, '1.2 成交前十', '今日成交额前十股票如下:')
report.set_picture('股票前十')
report.set_paragraph(1, '2.宽基指数', '以下是宽基指数表现:')
report.set_picture('宽基')
report.set_paragraph(1, '3.风格指数', '以下是风格指数表现:')
report.set_picture('风格')
report.set_paragraph(1, '4.中证行业指数', '以下是中证行业指数表现:')
report.set_picture('中证行业')
report.set_paragraph(1, '5.成交量', '以下是历史成交量趋势:')
report.set_picture('成交额')
document.save(store_path + 'report_stock.docx')
print('报告生成完毕!')
if __name__ == '__main__':
store_path = ''
get_word(store_path)
免责声明:本文由作者参考相关资料,并结合自身实践和思考独立完成,对全文内容的准确性、完整性或可靠性不作任何保证。同时,文中提及的数据仅作为举例使用,不构成推荐;文中所有观点均不构成任何投资建议。请读者仔细阅读本声明,若读者阅读此文章,默认知晓此声明。