生成pdf

parent 3bf46d55
...@@ -903,7 +903,7 @@ ...@@ -903,7 +903,7 @@
<div class="box0"> <div class="box0">
<div class="cover_head dtable"> <div class="cover_head dtable">
<div class="dcell"> <div class="dcell">
<img src="./img/logo.png" alt="" class="cover_logo"> <img src={{logo}} alt="" class="cover_logo">
</div> </div>
<div class="dcell"> <div class="dcell">
<div class="cover_line"></div> <div class="cover_line"></div>
...@@ -920,13 +920,13 @@ ...@@ -920,13 +920,13 @@
敬呈 敬呈
</span> </span>
<span class="cover_name"> <span class="cover_name">
王晶 {{customer_name}}
</span> </span>
<span class="cover_sir"> <span class="cover_sir">
先生 先生
</span> </span>
</div> </div>
<img src="./img/cover-back.png" alt="" class="cover_back"> <img src={{cover_back}} alt="" class="cover_back">
<div class="cover_date"> <div class="cover_date">
<div class="cover_time"> <div class="cover_time">
2020.10 2020.10
...@@ -985,7 +985,7 @@ ...@@ -985,7 +985,7 @@
</div> </div>
<div class="page_head dcell"> <div class="page_head dcell">
<div class="dcell"> <div class="dcell">
<img src="./img/logo.png" alt="" class="page_logo"> <img src={{logo}} alt="" class="page_logo">
</div> </div>
<div class="dcell"> <div class="dcell">
<div class="page_line"></div> <div class="page_line"></div>
...@@ -1167,9 +1167,6 @@ ...@@ -1167,9 +1167,6 @@
<td> <td>
{{value[12]["profit"]}} {{value[12]["profit"]}}
</td> </td>
<!-- <td>-->
<!-- {{value[13]["profit"]}}-->
<!-- </td>-->
</tr> </tr>
<tr> <tr>
<td> <td>
...@@ -1211,11 +1208,6 @@ ...@@ -1211,11 +1208,6 @@
<td> <td>
{{value[12]["net_amount"]}} {{value[12]["net_amount"]}}
</td> </td>
<!-- <td>-->
<!-- {{value[13]["net_amount"]}}-->
<!-- </td> <td>-->
<!-- {{value[13]["net_amount"]}}-->
<!-- </td>-->
</tr> </tr>
{%endfor%} {%endfor%}
</table> </table>
...@@ -1234,7 +1226,7 @@ ...@@ -1234,7 +1226,7 @@
</div> </div>
<div class="page_head dcell"> <div class="page_head dcell">
<div class="dcell"> <div class="dcell">
<img src="./img/logo.png" alt="" class="page_logo"> <img src={{logo}} alt="" class="page_logo">
</div> </div>
<div class="dcell"> <div class="dcell">
<div class="page_line"></div> <div class="page_line"></div>
...@@ -1460,7 +1452,7 @@ ...@@ -1460,7 +1452,7 @@
</div> </div>
<div class="page_head dcell"> <div class="page_head dcell">
<div class="dcell"> <div class="dcell">
<img src="./img/logo.png" alt="" class="page_logo"> <img src={{logo}} alt="" class="page_logo">
</div> </div>
<div class="dcell"> <div class="dcell">
<div class="page_line"></div> <div class="page_line"></div>
...@@ -1612,7 +1604,7 @@ ...@@ -1612,7 +1604,7 @@
</div> </div>
<div class="page_head dcell"> <div class="page_head dcell">
<div class="dcell"> <div class="dcell">
<img src="./img/logo.png" alt="" class="page_logo"> <img src={{logo}} alt="" class="page_logo">
</div> </div>
<div class="dcell"> <div class="dcell">
<div class="page_line"></div> <div class="page_line"></div>
...@@ -1697,7 +1689,7 @@ ...@@ -1697,7 +1689,7 @@
</div> </div>
<div class="page_head dcell"> <div class="page_head dcell">
<div class="dcell"> <div class="dcell">
<img src="./img/logo.png" alt="" class="page_logo"> <img src={{logo}} alt="" class="page_logo">
</div> </div>
<div class="dcell"> <div class="dcell">
<div class="page_line"></div> <div class="page_line"></div>
...@@ -1921,7 +1913,7 @@ ...@@ -1921,7 +1913,7 @@
</div> </div>
<div class="page_head dcell"> <div class="page_head dcell">
<div class="dcell"> <div class="dcell">
<img src="./img/logo.png" alt="" class="page_logo"> <img src={{logo}} alt="" class="page_logo">
</div> </div>
<div class="dcell"> <div class="dcell">
<div class="page_line"></div> <div class="page_line"></div>
...@@ -2004,7 +1996,7 @@ ...@@ -2004,7 +1996,7 @@
<div class="financial_show dtable"> <div class="financial_show dtable">
<div class="financial_left dcell"> <div class="financial_left dcell">
<div class="financial_scene"> <div class="financial_scene">
<img src="./img/scene.png" alt="" class="financial_scene_img"> <img src={{scene}}" alt="" class="financial_scene_img">
<div class="financial_scene_text"> <div class="financial_scene_text">
我们挣的是⻆度和变化的钱⽽不是纠正市场错 误的钱,市场永远是正确的,关键是在其正确 被反复证明后的逆向⽽⾏,⼀定是避开它的正 确被展开的过程 。 我们挣的是⻆度和变化的钱⽽不是纠正市场错 误的钱,市场永远是正确的,关键是在其正确 被反复证明后的逆向⽽⾏,⼀定是避开它的正 确被展开的过程 。
</div> </div>
...@@ -2015,7 +2007,7 @@ ...@@ -2015,7 +2007,7 @@
</div> </div>
<div class="financial_show_right dcell"> <div class="financial_show_right dcell">
<div class="financial_team"> <div class="financial_team">
<img src="./img/team.png" alt="" class="financial_team_img"> <img src={{team}} alt="" class="financial_team_img">
</div> </div>
</div> </div>
</div> </div>
......
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
import logging import logging
logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.INFO)
from app.api.engine import tamp_fund_engine, TAMP_SQL, tamp_product_engine from app.api.engine import tamp_fund_engine, TAMP_SQL
from app.utils.week_evaluation import * from app.utils.week_evaluation import *
...@@ -32,66 +32,35 @@ def get_nav(fund, start_date, rollback=False, invest_type='public'): ...@@ -32,66 +32,35 @@ def get_nav(fund, start_date, rollback=False, invest_type='public'):
Returns:df[DataFrame]: 索引为净值公布日, 列为复权净值的净值表; 查询失败则返回None Returns:df[DataFrame]: 索引为净值公布日, 列为复权净值的净值表; 查询失败则返回None
""" """
with TAMP_SQL(tamp_fund_engine) as tamp_fund: with TAMP_SQL(tamp_fund_engine) as tamp_product:
tamp_fund_session = tamp_fund.session tamp_product_session = tamp_product.session
if invest_type == 'public': if invest_type == 'public':
sql = "SELECT ts_code, end_date, adj_nav FROM public_fund_nav " \ sql = "SELECT ts_code, end_date, adj_nav FROM public_fund_nav " \
"WHERE ts_code='{}'".format(fund) "WHERE ts_code='{}'".format(fund)
cur = tamp_fund_session.execute(sql) cur = tamp_product_session.execute(sql)
data = cur.fetchall() data = cur.fetchall()
df1 = pd.DataFrame(list(data), columns=['fund_id', 'end_date', 'adj_nav']).dropna(how='any') df = pd.DataFrame(list(data), columns=['fund_id', 'end_date', 'adj_nav']).dropna(how='any')
df1.rename({'ts_code': 'fund_id'}, axis=1, inplace=True) df.rename({'ts_code': 'fund_id'}, axis=1, inplace=True)
else: else:
sql = "SELECT fund_id, price_date, cumulative_nav FROM fund_nav " \
"WHERE fund_id='{}'".format(fund)
# df = pd.read_sql(sql, con).dropna(how='any')
cur = tamp_fund_session.execute(sql)
data = cur.fetchall()
df1 = pd.DataFrame(data, columns=['fund_id', 'price_date', 'cumulative_nav']).dropna(how='any')
df1.rename({'price_date': 'end_date', 'cumulative_nav': 'adj_nav'}, axis=1, inplace=True)
# if df1['adj_nav'].count() == 0:
# logging.log(logging.ERROR, "CAN NOT FIND {}".format(fund))
# return None
df1['end_date'] = pd.to_datetime(df1['end_date'])
if rollback and df1['end_date'].min() < start_date < df1['end_date'].max():
while start_date not in list(df1['end_date']):
start_date -= datetime.timedelta(days=1)
df1 = df1[df1['end_date'] >= start_date]
df1.drop_duplicates(subset='end_date', inplace=True, keep='first')
# df1.set_index('end_date', inplace=True)
# df1.sort_index(inplace=True, ascending=True)
with TAMP_SQL(tamp_product_engine) as tamp_product:
tamp_product_session = tamp_product.session
if invest_type == "private":
sql = "SELECT fund_id, price_date, cumulative_nav FROM fund_nav " \ sql = "SELECT fund_id, price_date, cumulative_nav FROM fund_nav " \
"WHERE fund_id='{}'".format(fund) "WHERE fund_id='{}'".format(fund)
# df = pd.read_sql(sql, con).dropna(how='any') # df = pd.read_sql(sql, con).dropna(how='any')
cur = tamp_product_session.execute(sql) cur = tamp_product_session.execute(sql)
data = cur.fetchall() data = cur.fetchall()
df2 = pd.DataFrame(data, columns=['fund_id', 'price_date', 'cumulative_nav']).dropna(how='any') df = pd.DataFrame(data, columns=['fund_id', 'price_date', 'cumulative_nav']).dropna(how='any')
df2.rename({'price_date': 'end_date', 'cumulative_nav': 'adj_nav'}, axis=1, inplace=True) df.rename({'price_date': 'end_date', 'cumulative_nav': 'adj_nav'}, axis=1, inplace=True)
# if df2['adj_nav'].count() == 0: if df['adj_nav'].count() == 0:
# logging.log(logging.ERROR, "CAN NOT FIND {}".format(fund)) logging.log(logging.ERROR, "CAN NOT FIND {}".format(fund))
# return None return None
df2['end_date'] = pd.to_datetime(df2['end_date']) df['end_date'] = pd.to_datetime(df['end_date'])
if rollback and df2['end_date'].min() < start_date < df2['end_date'].max(): if rollback and df['end_date'].min() < start_date < df['end_date'].max():
while start_date not in list(df2['end_date']): while start_date not in list(df['end_date']):
start_date -= datetime.timedelta(days=1) start_date -= datetime.timedelta(days=1)
df2 = df2[df2['end_date'] >= start_date] df = df[df['end_date'] >= start_date]
df2.drop_duplicates(subset='end_date', inplace=True, keep='first')
# df2.set_index('end_date', inplace=True)
# df2.sort_index(inplace=True, ascending=True)
df = pd.concat([df1, df2])
df.drop_duplicates(subset='end_date', inplace=True, keep='first') df.drop_duplicates(subset='end_date', inplace=True, keep='first')
df.set_index('end_date', inplace=True) df.set_index('end_date', inplace=True)
df.sort_index(inplace=True, ascending=True) df.sort_index(inplace=True, ascending=True)
...@@ -132,10 +101,10 @@ def get_trade_cal(): ...@@ -132,10 +101,10 @@ def get_trade_cal():
Returns:df[DataFrame]: 索引为交易日, 列为交易日的上交所交易日历表 Returns:df[DataFrame]: 索引为交易日, 列为交易日的上交所交易日历表
""" """
with TAMP_SQL(tamp_fund_engine) as tamp_fund: with TAMP_SQL(tamp_fund_engine) as tamp_product:
tamp_fund_session = tamp_fund.session tamp_product_session = tamp_product.session
sql = 'SELECT cal_date FROM stock_trade_cal WHERE is_open=1' sql = 'SELECT cal_date FROM stock_trade_cal WHERE is_open=1'
cur = tamp_fund_session.execute(sql) cur = tamp_product_session.execute(sql)
data = cur.fetchall() data = cur.fetchall()
df = pd.DataFrame(list(data), columns=['cal_date']).dropna(how='all') df = pd.DataFrame(list(data), columns=['cal_date']).dropna(how='all')
# df = pd.read_sql(sql, con) # df = pd.read_sql(sql, con)
...@@ -153,30 +122,20 @@ def get_manager(invest_type): ...@@ -153,30 +122,20 @@ def get_manager(invest_type):
Returns: Returns:
""" """
with TAMP_SQL(tamp_fund_engine) as tamp_fund: with TAMP_SQL(tamp_fund_engine) as tamp_product:
tamp_fund_session = tamp_fund.session tamp_product_session = tamp_product.session
if invest_type == 'public': if invest_type == 'public':
sql = 'SELECT ts_code, name FROM public_fund_manager WHERE end_date IS NULL' sql = 'SELECT ts_code, name FROM public_fund_manager WHERE end_date IS NULL'
# df = pd.read_sql(sql, con) # df = pd.read_sql(sql, con)
cur = tamp_fund_session.execute(sql) cur = tamp_product_session.execute(sql)
data = cur.fetchall() data = cur.fetchall()
df1 = pd.DataFrame(list(data), columns=['ts_code', 'name']) df = pd.DataFrame(list(data), columns=['ts_code', 'name'])
else: else:
sql = 'SELECT fund_id, fund_manager_id, management_start_date FROM fund_manager_mapping' sql = 'SELECT fund_id, fund_manager_id FROM fund_manager_mapping'
# df = pd.read_sql(sql, con) # df = pd.read_sql(sql, con)
cur = tamp_fund_session.execute(sql)
data = cur.fetchall()
df1 = pd.DataFrame(list(data), columns=['fund_id', 'fund_manager_id', 'management_start_date'])
with TAMP_SQL(tamp_product_engine) as tamp_product:
tamp_product_session = tamp_product.session
if invest_type == 'private':
sql = 'SELECT fund_id, fund_manager_id, management_start_date FROM fund_manager_mapping'
cur = tamp_product_session.execute(sql) cur = tamp_product_session.execute(sql)
data = cur.fetchall() data = cur.fetchall()
df2 = pd.DataFrame(list(data), columns=['fund_id', 'fund_manager_id', 'management_start_date']) df = pd.DataFrame(list(data), columns=['fund_id', 'fund_manager_id'])
df = pd.concat([df1, df2]).drop_duplicates()
return df return df
...@@ -190,47 +149,31 @@ def get_fund_info(end_date, invest_type): ...@@ -190,47 +149,31 @@ def get_fund_info(end_date, invest_type):
Returns: Returns:
[type]: [description] [type]: [description]
""" """
with TAMP_SQL(tamp_fund_engine) as tamp_fund: with TAMP_SQL(tamp_fund_engine) as tamp_product:
tamp_fund_session = tamp_fund.session tamp_product_session = tamp_product.session
if invest_type == 'public': if invest_type == 'public':
sql = "SELECT ts_code, fund_type, management FROM public_fund_basic " \ sql = "SELECT ts_code, fund_type, management FROM public_fund_basic " \
"WHERE delist_date IS NULL AND (due_date IS NULL OR due_date>'{}')".format(end_date.strftime('%Y%m%d')) "WHERE delist_date IS NULL AND (due_date IS NULL OR due_date>'{}')".format(end_date.strftime('%Y%m%d'))
# df = pd.read_sql(sql, con).dropna(how='all') # df = pd.read_sql(sql, con).dropna(how='all')
cur = tamp_fund_session.execute(sql) cur = tamp_product_session.execute(sql)
data = cur.fetchall() data = cur.fetchall()
df1 = pd.DataFrame(list(data), columns=['fund_id', 'fund_type', 'management']) df = pd.DataFrame(list(data), columns=['ts_code', 'fund_type', 'management'])
# manager_info = get_manager(invest_type) manager_info = get_manager(invest_type)
# df1.rename({'ts_code': 'fund_id'}, axis=1, inplace=True) df.rename({'ts_code': 'fund_id'}, axis=1, inplace=True)
# df = pd.merge(df, manager_info, how="left", on='fund_id') df = pd.merge(df, manager_info, how="left", on='fund_id')
else: else:
sql = "SELECT id, substrategy FROM fund_info WHERE delete_tag=0 " \
"AND substrategy!=-1"
cur = tamp_fund_session.execute(sql)
data = cur.fetchall()
df1 = pd.DataFrame(list(data), columns=['fund_id', 'substrategy'])
# df = pd.read_sql(sql, con).dropna(how='all')
# df1.rename({'id': 'fund_id'}, axis=1, inplace=True)
# manager_info = get_manager(invest_type)
# df = pd.merge(df, manager_info, how="inner", on='fund_id')
with TAMP_SQL(tamp_product_engine) as tamp_product:
tamp_product_session = tamp_product.session
if invest_type == "private":
sql = "SELECT id, substrategy FROM fund_info WHERE delete_tag=0 " \ sql = "SELECT id, substrategy FROM fund_info WHERE delete_tag=0 " \
"AND substrategy!=-1" "AND substrategy!=-1"
cur = tamp_product_session.execute(sql) cur = tamp_product_session.execute(sql)
data = cur.fetchall() data = cur.fetchall()
df2 = pd.DataFrame(list(data), columns=['fund_id', 'substrategy']) df = pd.DataFrame(list(data), columns=['id', 'substrategy'])
# df = pd.read_sql(sql, con).dropna(how='all') # df = pd.read_sql(sql, con).dropna(how='all')
# df2.rename({'id': 'fund_id'}, axis=1, inplace=True) df.rename({'id': 'fund_id'}, axis=1, inplace=True)
# manager_info = get_manager(invest_type)
manager_info = get_manager(invest_type) manager_info = get_manager(invest_type)
df = pd.concat([df1, df2]).drop_duplicates()
df = pd.merge(df, manager_info, how="inner", on='fund_id') df = pd.merge(df, manager_info, how="inner", on='fund_id')
return df return df
...@@ -333,12 +276,11 @@ def fund_rank(start_date, end_date, invest_type='private'): ...@@ -333,12 +276,11 @@ def fund_rank(start_date, end_date, invest_type='private'):
continue continue
n = get_frequency(df) n = get_frequency(df)
except Exception as e: except Exception as e:
logging.log(logging.ERROR, repr(e)) # logging.log(logging.ERROR, repr(e))
logging.log(logging.INFO, 'Skipped {}'.format(fund)) logging.log(logging.INFO, 'Skipped {}'.format(fund))
skipped_funds.append(fund)
continue continue
df = resample(df, trading_cal, n, simple_flag=False) df = resample(df, trading_cal, n)
try: try:
_ = get_frequency(df) _ = get_frequency(df)
...@@ -360,8 +302,7 @@ def fund_rank(start_date, end_date, invest_type='private'): ...@@ -360,8 +302,7 @@ def fund_rank(start_date, end_date, invest_type='private'):
down_risk = downside_risk(sim_return, bank_rate=0.015, n=n) down_risk = downside_risk(sim_return, bank_rate=0.015, n=n)
sor_ratio = sortino_ratio(ex_return, down_risk, n) sor_ratio = sortino_ratio(ex_return, down_risk, n)
manager = fund_info[fund_info['fund_id'] == fund].groupby("management_start_date").last() manager = fund_info[fund_info['fund_id'] == fund]['fund_manager_id'].values
manager = manager['fund_manager_id'].values
# management = fund_info[fund_info['fund_id'] == fund]['management'].values # management = fund_info[fund_info['fund_id'] == fund]['management'].values
row = pd.Series([fund, rng_return, ann_return, drawdown, shp_ratio, row = pd.Series([fund, rng_return, ann_return, drawdown, shp_ratio,
...@@ -383,8 +324,8 @@ def fund_rank(start_date, end_date, invest_type='private'): ...@@ -383,8 +324,8 @@ def fund_rank(start_date, end_date, invest_type='private'):
if __name__ == '__main__': if __name__ == '__main__':
end_date = datetime.datetime.now() - datetime.timedelta(days=1) end_date = datetime.datetime.now() - datetime.timedelta(days=1)
start_date = cal_date(end_date, 'Y', 1) start_date = cal_date(end_date, 'Y', 1)
fund_rank = fund_rank(start_date, end_date, invest_type="private") fund_rank = fund_rank(start_date, end_date, False)
fund_rank.to_csv("fund_rank.csv", encoding='gbk') # fund_rank.to_csv("fund_rank.csv", encoding='gbk')
df = pd.read_csv('fund_rank.csv') # df = pd.read_csv('fund_rank.csv')
# df.to_sql("fund_rank", con, if_exists='replace') # df.to_sql("fund_rank", con, if_exists='replace')
# con.close() # con.close()
...@@ -17,7 +17,7 @@ def html_to_pdf(source_path, target_path): ...@@ -17,7 +17,7 @@ def html_to_pdf(source_path, target_path):
'encoding': "utf-8", 'encoding': "utf-8",
# 'page-size': 'A5', # 'page-size': 'A5',
# 'page-width': '300mm', # 'page-width': '300mm',
# 'page-height': 'auto', 'page-height': '2.3mm',
'margin-top': '0mm', 'margin-top': '0mm',
'margin-right': '0mm', 'margin-right': '0mm',
'margin-bottom': '0mm', 'margin-bottom': '0mm',
......
...@@ -3,6 +3,7 @@ import uuid ...@@ -3,6 +3,7 @@ import uuid
from jinja2 import PackageLoader, Environment from jinja2 import PackageLoader, Environment
from app.api.engine import work_dir, pdf_folder, template_folder
from app.service.portfolio_diagnose import portfolio_diagnose from app.service.portfolio_diagnose import portfolio_diagnose
from app.service.result_service_v2 import UserCustomerResultAdaptor from app.service.result_service_v2 import UserCustomerResultAdaptor
import numpy as np import numpy as np
...@@ -80,8 +81,6 @@ class DataIntegrate: ...@@ -80,8 +81,6 @@ class DataIntegrate:
self.single_fund_data_list = [] self.single_fund_data_list = []
portfolio_evaluation = portfolio_diagnose.old_portfolio_evaluation() portfolio_evaluation = portfolio_diagnose.old_portfolio_evaluation()
radar_chart_data = portfolio_diagnose.single_fund_radar() radar_chart_data = portfolio_diagnose.single_fund_radar()
print('***************************')
print(portfolio_evaluation)
for i in range(len(portfolio_evaluation)): for i in range(len(portfolio_evaluation)):
if portfolio_evaluation[i]['status'] == '保留': if portfolio_evaluation[i]['status'] == '保留':
portfolio_evaluation[i]['status'] = '<div class="self_type fl">保留</div>' portfolio_evaluation[i]['status'] = '<div class="self_type fl">保留</div>'
...@@ -167,8 +166,15 @@ class DataIntegrate: ...@@ -167,8 +166,15 @@ class DataIntegrate:
def render_data(self): def render_data(self):
# 全部数据 # 全部数据
data = {'customer_name': self.customer_name, 'customer_gender': '女', data = {
'year_month': '2020年10月', 'ifa_company': '飞度工作室', 'cover_back': template_folder + '/v2/img/cover-back.png',
'logo': template_folder + '/v2/img/logo.png',
'scene': template_folder + '/v2/img/scene/png',
'team': template_folder + '/v2/img/team.png',
'customer_name': self.customer_name,
'customer_gender': '女',
'year_month': '2020年10月',
'ifa_company': '飞度工作室',
'title': '10月综述', 'brand_name': '飞度工作室', 'title': '10月综述', 'brand_name': '飞度工作室',
'customer_old': 42, 'customer_level': '平衡型', 'customer_old': 42, 'customer_level': '平衡型',
# 'new_evaluation': self.new_evaluation, # 'new_evaluation': self.new_evaluation,
...@@ -219,10 +225,10 @@ class DataIntegrate: ...@@ -219,10 +225,10 @@ class DataIntegrate:
# with open(save_file, 'w', encoding="utf-8") as f: # with open(save_file, 'w', encoding="utf-8") as f:
# f.write(monthReport_html) # f.write(monthReport_html)
save_file = "app/html/v2/monthReportV2.html" # save_file = "app/html/v2/monthReportV2.html"
with open(save_file, 'w', encoding="utf-8") as f: # with open(save_file, 'w', encoding="utf-8") as f:
f.write(monthReport_html) # f.write(monthReport_html)
# html_to_pdf(monthReport_html, '/Users/pengxiong/Desktop/fund_report/app/pdf/%s.pdf' % str(uuid.uuid4())) html_to_pdf(monthReport_html, pdf_folder + str(uuid.uuid4()))
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment