├── AuthorProfile.jpg ├── GenerateHTML.py ├── LICENSE ├── LeanReportCreator.py ├── README.md ├── json └── sample.json └── outputs ├── Report.html ├── annual-returns.png ├── asset-allocation-all.png ├── asset-allocation-equity.png ├── crisis-2009q1.png ├── crisis-2009q2.png ├── crisis-9-11.png ├── crisis-aug07.png ├── crisis-dotcom.png ├── crisis-flash-crash.png ├── crisis-fukushima-melt-down-2011.png ├── crisis-gfc-crash.png ├── crisis-lehman-brothers.png ├── crisis-low-volatility-bull-market.png ├── crisis-mar08.png ├── crisis-recovery.png ├── crisis-sept08.png ├── crisis-us-downgrade-european-debt-crisis.png ├── crisis-us-housing-bubble-2003.png ├── cumulative-return.png ├── daily-returns.png ├── distribution-of-monthly-returns.png ├── drawdowns.png ├── leverage.png ├── monthly-returns.png ├── net-holdings.png ├── rolling-portfolio-beta-to-equity.png ├── rolling-sharpe-ratio(6-month).png └── strategy-statistics.json /AuthorProfile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/AuthorProfile.jpg -------------------------------------------------------------------------------- /GenerateHTML.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import os 3 | import os.path 4 | import re 5 | import json 6 | 7 | def Base64(image): 8 | if not os.path.isfile(image) : 9 | return "" 10 | return 'data:image/png;base64,' + base64.b64encode(open(image, "rb").read()).decode('utf-8').replace('\n', '') 11 | 12 | def MethodGetTableHTML(title, ls): 13 | ret = ''' 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 |
''' + title + '''
''' + str(ls[0][0]) + ':' + '''''' + ("✔" if ls[0][1] == 1 else ("✖" if ls[0][1] == 0 else str(ls[0][1]))) + '''
''' + str(ls[1][0]) + ':' + '''''' + ("✔" if ls[1][1] == 1 else ("✖" if ls[1][1] == 0 else str(ls[1][1]))) + '''
''' + str(ls[2][0]) + ':' + '''''' + ("✔" if ls[2][1] == 1 else ("✖" if ls[2][1] == 0 else str(ls[2][1]))) + '''
''' + str(ls[3][0]) + ':' + '''''' + ("✔" if ls[3][1] == 1 else ("✖" if ls[3][1] == 0 else str(ls[3][1]))) + '''
''' + str(ls[4][0]) + ':' + '''''' + (str(ls[4][1]) if type(ls[4][1])!=list else ", ".join(ls[4][1])) + '''
32 |
''' 33 | return ret 34 | 35 | def MethodGetImageBoxHTML(title, url, col = 4): 36 | if not url: 37 | return "" 38 | ret = ''' 39 |
40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 51 | 52 | 53 |
''' + title + '''
49 | ''' + (( '''''' ) if url else "") + ''' 50 |
54 |
''' 55 | return ret 56 | 57 | def MethodGetCrisisImageHTML(ls,crisis_list, outdir): 58 | crisis_title = ["Crisis "+ x for x in crisis_list] 59 | crisis_image = [outdir + "/" + re.sub(r' ','-',x.lower())+".png" for x in crisis_title ] 60 | 61 | ret = ''' 62 |
63 | ''' 64 | count = ls[0] 65 | index = ls[1] 66 | for i in range(index,len(crisis_title)): 67 | if os.path.isfile(crisis_image[i]): 68 | ls[2] = True 69 | if count % 3 == 0 : 70 | ret += '''
''' 71 | ret += MethodGetImageBoxHTML(crisis_title[i], Base64(crisis_image[i])) 72 | elif count % 3 == 1 : 73 | ret += MethodGetImageBoxHTML(crisis_title[i], Base64(crisis_image[i])) 74 | else: 75 | ret += MethodGetImageBoxHTML(crisis_title[i], Base64(crisis_image[i])) 76 | ret += '''
''' 77 | count += 1 78 | ls[0], ls[1] = count, i 79 | if count == 5*3: 80 | ls[0] = 0 81 | break 82 | ls[1] += 1 83 | 84 | if count % 3 != 0: 85 | ret += '''
''' 86 | ret += '''''' 87 | return ret 88 | 89 | def MethodGetCrisisPageHTML(outdir): 90 | crisis_list = ["Dotcom","9-11","US Housing Bubble 2003","Lehman Brothers","Flash Crash", 91 | "Aug07","Mar08","Sept08","2009Q1","2009Q2", 92 | "US Downgrade-European Debt Crisis","Fukushima Melt Down 2011","ECB IR Event 2012", 93 | "Apr14","Oct14","Fall2015", 94 | "Low Volatility Bull Market","GFC Crash","Recovery","New Normal"] 95 | ls = [0,0,False] 96 | ret = '''''' 97 | while(ls[1] < len(crisis_list)): 98 | tmp = ''' 99 |
100 |
101 |
102 | 103 |
104 |
Backtest Crisis Analysis
105 |
''' + rightHeaderText + '''
106 |
''' + MethodGetCrisisImageHTML(ls, crisis_list,outdir) + ''' 107 | 112 |
''' 113 | if ls[2]: 114 | ret += tmp 115 | ls[2] = False 116 | return ret 117 | 118 | def MethodGetAssetAllocationImageHTML(ls,asset_list, outdir): 119 | asset_title = asset_list 120 | asset_image = [outdir + "/" + "asset-allocation-"+x+".png" for x in asset_title ] 121 | 122 | ret = ''' 123 |
124 | ''' 125 | count = ls[0] 126 | index = ls[1] 127 | for i in range(index,len(asset_title)): 128 | if os.path.isfile(asset_image[i]): 129 | ls[2] = True 130 | if count % 3 == 0 : 131 | ret += '''
''' 132 | ret += MethodGetImageBoxHTML(asset_title[i], Base64(asset_image[i])) 133 | elif count % 3 == 1 : 134 | ret += MethodGetImageBoxHTML(asset_title[i], Base64(asset_image[i])) 135 | else: 136 | ret += MethodGetImageBoxHTML(asset_title[i], Base64(asset_image[i])) 137 | ret += '''
''' 138 | count += 1 139 | ls[0], ls[1] = count, i 140 | if count == 5*3: 141 | ls[0] = 0 142 | break 143 | ls[1] += 1 144 | 145 | if count % 3 != 0: 146 | ret += '''
''' 147 | ret += '''''' 148 | return ret 149 | 150 | def MethodGetAssetAllocationPageHTML(outdir): 151 | asset_list = ['Equity', 'Option', 'Commodity', 'Forex', 'Future', 'Cfd', 'Crypto'] 152 | ls = [0,0,False] 153 | ret = '''''' 154 | while(ls[1] < len(asset_list)): 155 | tmp = ''' 156 |
157 |
158 |
159 | 160 |
161 |
Backtest Crisis Analysis
162 |
''' + rightHeaderText + '''
163 |
''' + MethodGetAssetAllocationImageHTML(ls, asset_list, outdir) + ''' 164 | 169 |
''' 170 | if ls[2]: 171 | ret += tmp 172 | ls[2] = False 173 | return ret 174 | 175 | rightHeaderText = "Basic Template Algorithm" 176 | footerId = "" 177 | strategyDescription = "Put your strategy description here:" 178 | authorProfile = "D:\fakepath\LeanReportCreatorInPython\AuthorProfile.jpg" 179 | authorName = "Xiang Li" 180 | authorBio = "Put your biography here." 181 | 182 | def GenerateHTMLReport(outdir): 183 | 184 | f = open(outdir + "/" + 'Report.html','w+') 185 | 186 | chartMonthlyReturns = Base64(outdir + "/" + "monthly-returns.png") 187 | chartCumulativeReturns = Base64(outdir + "/" + "cumulative-return.png") 188 | chartAnnualReturns = Base64(outdir + "/" + "annual-returns.png") 189 | chartReturnsHistogram = Base64(outdir + "/" + "distribution-of-monthly-returns.png") 190 | chartAssetAllocation = Base64(outdir + "/" + "asset-allocation-all.png") 191 | chartDrawdown = Base64(outdir + "/" + "drawdowns.png") 192 | chartDailyReturns = Base64(outdir + "/" + "daily-returns.png") 193 | chartRollingBeta = Base64(outdir + "/" + "rolling-portfolio-beta-to-equity.png") 194 | chartRollingSP = Base64(outdir + "/" + "rolling-sharpe-ratio(6-month).png") 195 | chartNetHoldings = Base64(outdir + "/" + "net-holdings.png") 196 | chartLeverage = Base64(outdir + "/" + "leverage.png") 197 | 198 | locationPrefix = "https://www.quantconnect.com/terminal" 199 | 200 | with open(outdir + "/" + "strategy-statistics.json") as ff: 201 | tmp = json.load(ff) 202 | keyCharacteristics = tmp["Key Characteristics"] 203 | keyStatistics = tmp["Key Statistics"] 204 | 205 | html = ''' 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 325 | 326 | 327 | 328 |
329 | 330 | 331 | 332 |
333 | 334 |
335 |
336 |
337 | 338 |
339 |
Strategy Report Summary
340 |
''' + rightHeaderText + '''
341 |
342 |
343 |

Strategy Report

344 |
345 |
346 | 347 | 348 | 349 | 352 | 353 | 354 | 355 | 356 | 360 | 361 | 362 |
350 | Strategy Description 351 |
357 |

''' + strategyDescription + '''

358 | 359 |
363 |
364 |
365 | 366 | 367 | 368 | 371 | 372 | 373 | 374 | 375 | 380 | 381 | 382 |
369 | About the Author ''' + authorName + ''' 370 |
376 | 377 |

''' + authorBio + '''

378 | 379 |
383 |
384 |
385 |
386 | ''' + MethodGetTableHTML('Key Characteristics', keyCharacteristics) + ''' 387 | ''' + MethodGetTableHTML('Key Statistics', keyStatistics) + ''' 388 | ''' + MethodGetImageBoxHTML('Monthly Returns', chartMonthlyReturns) + ''' 389 |
390 |
391 | ''' + MethodGetImageBoxHTML('Cumulative Returns', chartCumulativeReturns, 12) + ''' 392 |
393 |
394 | ''' + MethodGetImageBoxHTML('Annual Returns', chartAnnualReturns) + ''' 395 | ''' + MethodGetImageBoxHTML('Return Histogram', chartReturnsHistogram) + ''' 396 | ''' + MethodGetImageBoxHTML('Asset Allocation', chartAssetAllocation) + ''' 397 |
398 |
399 | ''' + MethodGetImageBoxHTML('Drawdown', chartDrawdown, 12) + ''' 400 |
401 |
402 | 407 |
408 | 409 |
410 |
411 |
412 | 413 |
414 |
Backtest Strategy Analysis
415 |
''' + rightHeaderText + '''
416 |
417 |
418 |
419 | ''' + MethodGetImageBoxHTML('Daily Returns', chartDailyReturns, 12) + ''' 420 |
421 |
422 | ''' + MethodGetImageBoxHTML('Rolling Portfolio Beta to Equity', chartRollingBeta, 12) + ''' 423 |
424 |
425 | ''' + MethodGetImageBoxHTML('Rolling Sharpe Ratio (6 Months)', chartRollingSP, 12) + ''' 426 |
427 |
428 | ''' + MethodGetImageBoxHTML('Net Holdings', chartNetHoldings, 12) + ''' 429 |
430 |
431 | ''' + MethodGetImageBoxHTML('Leverage', chartLeverage, 12) + ''' 432 |
433 |
434 | 439 |
440 | ''' + MethodGetCrisisPageHTML(outdir) + ''' 441 | ''' + MethodGetAssetAllocationPageHTML(outdir) + ''' 442 | 443 | ''' 444 | 445 | f.write(html) 446 | f.close() 447 | 448 | dir_name = outdir 449 | test = os.listdir(dir_name) 450 | 451 | for item in test: 452 | if item.endswith(".png") or item.endswith(".json"): 453 | os.remove(os.path.join(dir_name, item)) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LeanReportCreator.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Apr 2 09:26:20 2018 4 | 5 | @author: Li Xiang 6 | """ 7 | 8 | import os 9 | import json 10 | import matplotlib 11 | import matplotlib.pyplot as plt 12 | import matplotlib.ticker as ticker 13 | font = {'family': 'Open Sans Condensed'} 14 | matplotlib.rc('font',**font) 15 | la = matplotlib.font_manager.FontManager() 16 | lu = matplotlib.font_manager.FontProperties(family = "Open Sans Condensed") 17 | from matplotlib.dates import DateFormatter 18 | import pandas as pd 19 | import numpy as np 20 | import matplotlib.colors as mcolors 21 | from datetime import date 22 | from datetime import datetime 23 | from datetime import timedelta 24 | import re 25 | import math 26 | import GenerateHTML 27 | 28 | class LeanReportCreator(object): 29 | 30 | def __init__(self, jsonfile, outdir = "outputs"): 31 | # Create output directory 32 | self.outdir = outdir 33 | if not os.path.exists(outdir): 34 | os.makedirs(outdir) 35 | # Read input file 36 | with open(jsonfile) as data_file: 37 | try: 38 | data = json.load(data_file) 39 | except ValueError: 40 | data = {"Charts": []} 41 | self.data = data 42 | # Parse the input file and make sure the input file is complete 43 | self.is_drawable = False 44 | if "Strategy Equity" in data["Charts"] and "Benchmark" in data["Charts"]: 45 | # Get value series from the input file 46 | strategySeries = data["Charts"]["Strategy Equity"]["Series"]["Equity"]["Values"] 47 | benchmarkSeries = data["Charts"]["Benchmark"]["Series"]["Benchmark"]["Values"] 48 | df_strategy = pd.DataFrame(strategySeries).set_index('x') 49 | df_benchmark = pd.DataFrame(benchmarkSeries).set_index('x') 50 | df_strategy = df_strategy[df_strategy > 0] 51 | df_benchmark = df_benchmark[df_benchmark > 0] 52 | df_strategy = df_strategy[~df_strategy.index.duplicated(keep='first')] 53 | df_benchmark = df_benchmark[~df_benchmark.index.duplicated(keep='first')] 54 | df = pd.concat([df_strategy,df_benchmark],axis = 1) 55 | df.columns = ['Strategy','Benchmark'] 56 | df = df.set_index(pd.to_datetime(df.index, unit='s')) 57 | self.df = df.fillna(method = 'ffill') 58 | self.df = df.fillna(method = 'bfill') 59 | self.initStrategyValue = self.df["Strategy"][0] 60 | self.initBenchmarkValue = self.df["Benchmark"][0] 61 | 62 | # Get order information from the input file 63 | self.orders = data["Orders"] 64 | df_this = self.df.copy() 65 | df_this.drop("Benchmark",1,inplace = True) 66 | df_values = pd.DataFrame() 67 | df_values["Value"] = [x["Value"] for x in self.orders.values()] 68 | df_values = df_values.set_index([[datetime.strptime(x["Time"][0:19], '%Y-%m-%dT%H:%M:%S') for x in self.orders.values()]]) 69 | df_this = df_this.join(df_values, how = "outer") 70 | df_this["Cash"] = -df_this["Value"] 71 | df_this["Cash"][0] = df_this["Strategy"][0] 72 | df_this.fillna(0,inplace = True) 73 | df_this["Cash"] = np.cumsum(df_this["Cash"]) 74 | df_this["Value"] = df_this["Strategy"] - df_this["Cash"] 75 | self.df_cash = df_this 76 | 77 | # Predefine this dataframe which is used to keep cash flow 78 | self.df_values = pd.DataFrame() 79 | 80 | # True means the essential information is complete 81 | self.is_drawable = True 82 | 83 | def cumulative_return(self, name = "cumulative-return.png", width = 11.5, height = 2.5): 84 | if self.is_drawable: 85 | # Prepare the dataset to be used for drawing charts 86 | df_this = self.df.copy() 87 | df_this["Strategy"] = (df_this["Strategy"]/self.initStrategyValue-1)*100 88 | df_this["Benchmark"] = (df_this["Benchmark"]/self.initBenchmarkValue-1)*100 89 | 90 | # Drawing charts 91 | plt.figure() 92 | ax = df_this.plot(color = ["#F5AE29","grey"]) 93 | fig = ax.get_figure() 94 | plt.xticks(rotation = 0,ha = 'center') 95 | plt.xlabel("") 96 | leg = ax.legend(["Strategy","Benchmark"],prop = {'weight':'bold'},frameon=False, loc = "upper left") 97 | ax.xaxis.set_major_formatter(DateFormatter("%b %Y")) 98 | plt.axhline(y = 0, color = 'grey') 99 | plt.setp(ax.spines.values(), color='grey') 100 | ax.spines['right'].set_visible(False) 101 | ax.spines['top'].set_visible(False) 102 | for line in leg.get_lines(): line.set_linewidth(4) 103 | plt.setp([ax.get_xticklines(), ax.get_yticklines()], color='grey') 104 | plt.ylabel("") 105 | plt.xlabel("") 106 | ax.yaxis.grid(True) 107 | fig.set_size_inches(width, height) 108 | fig.savefig(self.outdir + "/" + name, dpi = 200, bbox_inches='tight') 109 | plt.cla() 110 | plt.clf() 111 | plt.close('all') 112 | return True 113 | 114 | def daily_returns(self, name = "daily-returns.png", width = 11.5, height = 2.5): 115 | if self.is_drawable: 116 | # Prepare the dataset to be used for drawing charts 117 | df_this = self.df.copy() 118 | df_this.drop("Benchmark",1,inplace = True) 119 | df_this = df_this.groupby([df_this.index.date]).apply(lambda x: x.tail(1)) 120 | df_this.index = df_this.index.droplevel(1) 121 | ret_strategy = np.array([self.initStrategyValue] + df_this["Strategy"].tolist()) 122 | ret_strategy = ret_strategy[1:]/ret_strategy[:-1] - 1 123 | df_this["Strategy"] = ret_strategy*100 124 | df_this.index = pd.to_datetime(df_this.index) 125 | if len(df_this) > 1: 126 | for i in range(len(df_this)-1): 127 | tmp_delta = df_this.index[i+1] - df_this.index[i] 128 | for j in range(1, tmp_delta.days): 129 | df_this.loc[df_this.index[i] + timedelta(j)] = 0 130 | df_this.loc[df_this.index[i] + timedelta(0.99)] = df_this.loc[df_this.index[i]] 131 | df_this.loc[df_this.index[i+1] + timedelta(0.99)] = df_this.loc[df_this.index[i+1]] 132 | df_this.sort_index(inplace = True) 133 | 134 | # Drawing charts 135 | plt.figure() 136 | ax = df_this.plot(color = "white", alpha=0) 137 | ax.fill_between(df_this.index.values,0,df_this['Strategy'], where = 0df_this['Strategy'], color = "grey",step = "pre") 139 | fig = ax.get_figure() 140 | plt.xticks(rotation = 0,ha = 'center') 141 | plt.ylabel("") 142 | plt.xlabel("") 143 | ax.xaxis.set_major_formatter(DateFormatter("%b %Y")) 144 | plt.axhline(y = 0, color = 'grey') 145 | ax.legend_.remove() 146 | plt.setp(ax.spines.values(), color='grey') 147 | plt.setp([ax.get_xticklines(), ax.get_yticklines()], color='grey') 148 | ax.spines['right'].set_visible(False) 149 | ax.spines['top'].set_visible(False) 150 | ax.yaxis.grid(True) 151 | fig.set_size_inches(width, height) 152 | fig.savefig(self.outdir + "/" + name, dpi = 200, bbox_inches='tight') 153 | plt.cla() 154 | plt.clf() 155 | plt.close('all') 156 | return True 157 | 158 | def drawdown(self,name = "drawdowns.png",width = 11.5, height = 2.5): 159 | if self.is_drawable: 160 | # Prepare the dataset to be used for drawing charts 161 | df_this = self.df.copy() 162 | df_this.drop("Benchmark",1,inplace = True) 163 | df_this["Drawdown"] = 1 164 | lastPeak = self.initStrategyValue 165 | for i in range(len(df_this)): 166 | if df_this.iloc[i,0] < lastPeak: 167 | df_this.iloc[i,1] = df_this.iloc[i,0]/lastPeak 168 | else: 169 | lastPeak = df_this.iloc[i,0] 170 | df_this["DDGroup"] = 0 171 | tmp = 0 172 | for i in range(1,len(df_this)): 173 | if df_this.iloc[i,1] != 1: 174 | df_this.iloc[i,2] = tmp 175 | else: 176 | continue 177 | if df_this.iloc[i-1,1] == 1: 178 | tmp += 1 179 | df_this.iloc[i,2] = tmp 180 | df_this["index"] = [i for i in range(len(df_this))] 181 | tmp_df = pd.DataFrame.from_dict({'MDD':df_this.groupby([df_this["DDGroup"]])['Drawdown'].min(), 182 | 'Offset':df_this.groupby([df_this["DDGroup"]])['Drawdown'].apply(lambda x: np.where(x == min(x))[0][0]), 183 | 'Start':df_this.groupby([df_this["DDGroup"]])['index'].first(), 184 | 'End':df_this.groupby([df_this["DDGroup"]])['index'].last()}) 185 | tmp_df.drop(tmp_df.index[[0]],inplace = True) 186 | tmp_df.sort_values("MDD",inplace = True) 187 | df_this = (df_this["Drawdown"] - 1)*100 188 | 189 | # Drawing charts 190 | plt.figure() 191 | tmp_colors = ["#FFCCCCCC","#FFE5CCCC","#FFFFCCCC","#E5FFCCCC","#CCFFCCCC"] 192 | tmp_texts = ["1st Worst","2nd Worst","3rd Worst","4th Worst","5th Worst"] 193 | ax = df_this.plot(color = "grey",zorder = 2) 194 | ax.fill_between(df_this.index.values,df_this,0, color = "grey",zorder = 3) 195 | for i in range(min(len(tmp_df),5)): 196 | tmp_start = df_this.index.values[int(tmp_df.iloc[i]["Start"])] 197 | tmp_end = df_this.index.values[int(tmp_df.iloc[i]["End"])] 198 | tmp_mid = df_this.index.values[int(tmp_df.iloc[i]["Offset"])+int(tmp_df.iloc[i]["Start"])] 199 | plt.axvspan(tmp_start, tmp_end,0,0.95, color = tmp_colors[i],zorder = 1) 200 | plt.axvline(tmp_mid, 0,0.95, ls = "dashed",color ="grey", zorder = 4, linewidth = 0.75) 201 | plt.text(tmp_mid,min(df_this)*0.75,tmp_texts[i], rotation = 90, zorder = 4) 202 | fig = ax.get_figure() 203 | plt.xticks(rotation = 0,ha = 'center') 204 | plt.ylabel("") 205 | plt.xlabel("") 206 | ax.xaxis.set_major_formatter(DateFormatter("%b %Y")) 207 | plt.axhline(y = 0, color = 'grey') 208 | plt.setp(ax.spines.values(), color='grey') 209 | plt.setp([ax.get_xticklines(), ax.get_yticklines()], color='grey') 210 | ax.spines['right'].set_visible(False) 211 | ax.spines['top'].set_visible(False) 212 | ax.yaxis.grid(True) 213 | fig.set_size_inches(width, height) 214 | fig.savefig(self.outdir + "/" + name, dpi = 200, bbox_inches='tight') 215 | plt.cla() 216 | plt.clf() 217 | plt.close('all') 218 | return True 219 | 220 | def monthly_returns(self, name = "monthly-returns.png",width = 3.5*2, height = 2.5*2): 221 | if self.is_drawable: 222 | # Prepare the dataset to be used for drawing charts 223 | df_this = self.df.copy() 224 | df_this.drop("Benchmark",1,inplace = True) 225 | df_this1 = df_this.groupby([df_this.index.year,df_this.index.month]).apply(lambda x: x.head(1)) 226 | df_this2 = df_this.groupby([df_this.index.year,df_this.index.month]).apply(lambda x: x.tail(1)) 227 | df_this1.index = df_this1.index.droplevel(2) 228 | df_this2.index = df_this2.index.droplevel(2) 229 | df_this = pd.concat([df_this1,df_this2],axis = 1) 230 | df_this["Return"] = (df_this.iloc[:,1] / df_this.iloc[:,0] - 1) * 100 231 | df_this = df_this.iloc[:,2] 232 | for i in range(1,df_this.index[0][1]): 233 | df_this.loc[df_this.index[0][0],i] = float("nan") 234 | df_this.sort_index(0,0,inplace = True) 235 | df_this = df_this.unstack() 236 | df_this = df_this.iloc[::-1] 237 | 238 | # Define the rules of color change 239 | def make_colormap(seq): 240 | seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3] 241 | cdict = {'red': [], 'green': [], 'blue': []} 242 | for i, item in enumerate(seq): 243 | if isinstance(item, float): 244 | r1, g1, b1 = seq[i - 1] 245 | r2, g2, b2 = seq[i + 1] 246 | cdict['red'].append([item, r1, r2]) 247 | cdict['green'].append([item, g1, g2]) 248 | cdict['blue'].append([item, b1, b2]) 249 | return mcolors.LinearSegmentedColormap('CustomMap', cdict) 250 | c = mcolors.ColorConverter().to_rgb 251 | c_map = make_colormap([c('#CC0000'),0.1,c('#FF0000'),0.2,c('#FF3333'), 252 | 0.3,c('#FF9933'),0.4,c('#FFFF66'),0.5,c('#FFFF99'), 253 | 0.6,c('#B2FF66'),0.7,c('#99FF33'),0.8, 254 | c('#00FF00'),0.9, c('#00CC00')]) 255 | 256 | # Drawing charts 257 | plt.figure() 258 | ax = plt.imshow(df_this, aspect='auto',cmap=c_map, interpolation='none',vmin = -10, vmax = 10) 259 | fig = ax.get_figure() 260 | fig.set_size_inches(3.5*2,2.5*2) 261 | plt.yticks(range(len(df_this.index.values)),df_this.index.values) 262 | plt.xticks(range(12),["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]) 263 | for (j,i),label in np.ndenumerate(df_this): 264 | plt.text(i,j,round(label,1),ha='center',va='center') 265 | plt.ylabel("") 266 | plt.xlabel("") 267 | fig.set_size_inches(width, height) 268 | fig.savefig(self.outdir + "/" + name, dpi = 200, bbox_inches='tight') 269 | plt.cla() 270 | plt.clf() 271 | plt.close('all') 272 | return True 273 | 274 | def annual_returns(self, name = "annual-returns.png",width = 3.5*2, height = 2.5*2): 275 | if self.is_drawable: 276 | # Prepare the dataset to be used for drawing charts 277 | df_this = self.df.copy() 278 | df_this.drop("Benchmark",1,inplace = True) 279 | df_this1 = df_this.groupby([df_this.index.year]).apply(lambda x: x.head(1)) 280 | df_this2 = df_this.groupby([df_this.index.year]).apply(lambda x: x.tail(1)) 281 | df_this1.index = df_this1.index.droplevel(1) 282 | df_this2.index = df_this2.index.droplevel(1) 283 | df_this = pd.concat([df_this1,df_this2],axis = 1) 284 | df_this["Return"] = (df_this.iloc[:,1] / df_this.iloc[:,0] - 1) * 100 285 | df_this = df_this.iloc[:,2] 286 | 287 | # Drawing charts 288 | plt.figure() 289 | ax = df_this.plot.barh(color = ["#428BCA"]) 290 | fig = ax.get_figure() 291 | plt.xticks(rotation = 0,ha = 'center') 292 | plt.axvline(x = 0, color = 'grey', linewidth = 0.75) 293 | vline = plt.axvline(x = np.mean(df_this),color = "red", ls = "dashed", label = "mean", linewidth = 0.75) 294 | plt.legend([vline],["mean"],loc='upper right', frameon=False) 295 | plt.setp(ax.spines.values(), color='grey') 296 | plt.setp([ax.get_xticklines(), ax.get_yticklines()], color='grey') 297 | ax.spines['right'].set_visible(False) 298 | ax.spines['top'].set_visible(False) 299 | plt.xlabel("") 300 | plt.ylabel("") 301 | ax.xaxis.grid(True) 302 | fig.set_size_inches(width, height) 303 | fig.savefig(self.outdir + "/" + name, dpi = 200, bbox_inches='tight') 304 | plt.cla() 305 | plt.clf() 306 | plt.close('all') 307 | return True 308 | 309 | def monthly_return_distribution(self, name = "distribution-of-monthly-returns.png",width = 3.5*2, height = 2.5*2): 310 | if self.is_drawable: 311 | # Prepare the dataset to be used for drawing charts 312 | df_this = self.df.copy() 313 | df_this.drop("Benchmark",1,inplace = True) 314 | df_this1 = df_this.groupby([df_this.index.year,df_this.index.month]).apply(lambda x: x.head(1)) 315 | df_this2 = df_this.groupby([df_this.index.year,df_this.index.month]).apply(lambda x: x.tail(1)) 316 | df_this1.index = df_this1.index.droplevel(2) 317 | df_this2.index = df_this2.index.droplevel(2) 318 | df_this = pd.concat([df_this1,df_this2],axis = 1) 319 | df_this["Return"] = (df_this.iloc[:,1] / df_this.iloc[:,0] - 1) * 100 320 | df_this["Group"] = np.floor(df_this["Return"]) 321 | tmp_mean = np.mean(df_this["Return"]) 322 | tmp_mean = 11 if tmp_mean > 10 else -11 if tmp_mean < -10 else tmp_mean 323 | df_this = df_this.iloc[:,[2,3]] 324 | df_this["Group"] = [x if x<=10 and x>=-10 else float("-Inf") if x<-10 else float("Inf") for x in df_this["Group"]] 325 | df_this = df_this.groupby([df_this["Group"]]).count() 326 | tmp_min = int(min(max(min(df_this.index.values),-11),0)) 327 | tmp_max = int(max(min(max(df_this.index.values), 11),0)) 328 | for i in range(max(tmp_min,-10), min(tmp_max,10)+1): 329 | if i not in df_this.index.values: 330 | tmp = df_this.iloc[0].copy() 331 | tmp[0] = 0 332 | tmp.name = np.float64(i) 333 | df_this = df_this.append(tmp,ignore_index = False) 334 | df_this.sort_index(inplace = True) 335 | df_this.index = [">10" if x == float("Inf") else "<-10" if x == float("-Inf") else int(x) for x in df_this.index] 336 | 337 | # Drawing charts 338 | plt.figure() 339 | ax = df_this.plot.bar(color = ["#F5AE29"]) 340 | fig = ax.get_figure() 341 | plt.xticks(rotation = 0,ha = 'center') 342 | plt.axvline(x = -tmp_min, color = 'grey', linewidth = 0.75) 343 | vline = plt.axvline(x = tmp_mean-tmp_min,color = "red", ls = "dashed", label = "mean", linewidth = 0.75) 344 | plt.legend([vline],["mean"],loc='upper left', frameon=False) 345 | plt.setp(ax.spines.values(), color='grey') 346 | plt.setp([ax.get_xticklines(), ax.get_yticklines()], color='grey') 347 | ax.spines['right'].set_visible(False) 348 | ax.spines['top'].set_visible(False) 349 | plt.xlabel("") 350 | plt.ylabel("") 351 | ax.yaxis.grid(True) 352 | fig.set_size_inches(width, height) 353 | fig.savefig(self.outdir + "/" + name, dpi = 200, bbox_inches='tight') 354 | plt.cla() 355 | plt.clf() 356 | plt.close('all') 357 | return True 358 | 359 | def crisis_events(self, width = 3.5*2, height = 2.5*2): 360 | if self.is_drawable: 361 | # Prepare the dataset to be used for drawing charts 362 | df_this = self.df.copy() 363 | start_date = ["2000-03-10","2001-09-11","2003-01-08","2008-08-01","2010-05-05", 364 | "2007-08-01","2008-03-01","2008-09-01","2009-01-01","2009-03-01", 365 | "2011-08-05","2011-03-16","2012-09-10", 366 | "2014-04-01","2014-10-01","2015-08-15", 367 | "2005-01-01","2007-08-01","2009-04-01","2013-01-01"] 368 | end_date = ["2000-09-10","2001-10-11","2003-02-07","2008-09-30","2010-05-10", 369 | "2007-08-31","2008-03-31","2008-09-30","2009-02-28","2009-05-31", 370 | "2011-09-05","2011-04-16","2012-10-10", 371 | "2014-04-30","2014-10-31","2015-09-30", 372 | "2007-07-31","2009-03-31","2012-12-31",str(date.today())] 373 | titles = ["Dotcom","9-11","US Housing Bubble 2003","Lehman Brothers","Flash Crash", 374 | "Aug07","Mar08","Sept08","2009Q1","2009Q2", 375 | "US Downgrade-European Debt Crisis","Fukushima Melt Down 2011","ECB IR Event 2012", 376 | "Apr14","Oct14","Fall2015", 377 | "Low Volatility Bull Market","GFC Crash","Recovery","New Normal"] 378 | 379 | # Drawing charts 380 | for i in range(len(start_date)): 381 | df_this_tmp = df_this[start_date[i]:end_date[i]].copy() 382 | if not len(df_this_tmp): 383 | continue 384 | df_this_tmp["Strategy"] = (df_this_tmp["Strategy"]/df_this_tmp["Strategy"][0]-1)*100 385 | df_this_tmp["Benchmark"] = (df_this_tmp["Benchmark"]/df_this_tmp["Benchmark"][0]-1)*100 386 | plt.figure() 387 | ax = df_this_tmp.plot(color = ["#F5AE29","grey"]) 388 | fig = ax.get_figure() 389 | plt.xticks(ha = 'center') 390 | plt.xlabel("") 391 | leg = ax.legend(["Strategy","Benchmark"],prop = {'weight':'bold'},frameon=False, loc = "upper left") 392 | ax.xaxis.set_major_formatter(DateFormatter("%Y-%m-%d")) 393 | for line in leg.get_lines(): line.set_linewidth(4) 394 | plt.axhline(y = 0, color = 'grey') 395 | plt.setp(ax.spines.values(), color='grey') 396 | plt.setp([ax.get_xticklines(), ax.get_yticklines()], color='grey') 397 | ax.spines['right'].set_visible(False) 398 | ax.spines['top'].set_visible(False) 399 | plt.xlabel("") 400 | plt.ylabel("") 401 | ax.yaxis.grid(True) 402 | fig.set_size_inches(width, height) 403 | fig.savefig(self.outdir + "/crisis-" +re.sub(r' ','-',titles[i].lower())+".png", dpi = 200, bbox_inches='tight') 404 | plt.cla() 405 | plt.clf() 406 | plt.close('all') 407 | return True 408 | 409 | def rolling_beta(self, name = "rolling-portfolio-beta-to-equity.png",width = 11.5, height = 2.5): 410 | if self.is_drawable: 411 | # Prepare the dataset to be used for drawing charts 412 | days_L = 252 413 | days_S = 126 414 | if len(set(self.df.index.date)) > days_L: 415 | df_this = self.df.copy() 416 | df_this = df_this.groupby([df_this.index.date]).apply(lambda x: x.tail(1)) 417 | df_this.index = df_this.index.droplevel(1) 418 | ret_strategy = np.array([self.initStrategyValue] + df_this["Strategy"].tolist()) 419 | ret_strategy = ret_strategy[1:]/ret_strategy[:-1] - 1 420 | df_this["Strategy"] = ret_strategy*100 421 | ret_benchmark = np.array([self.initBenchmarkValue] + df_this["Benchmark"].tolist()) 422 | ret_benchmark = ret_benchmark[1:]/ret_benchmark[:-1] - 1 423 | df_this["Benchmark"] = ret_benchmark*100 424 | df_this["Beta6mo"] = float("nan") 425 | df_this["Beta12mo"] = float("nan") 426 | for i in range(days_L, len(df_this)): 427 | cov_matrix = np.cov(df_this["Strategy"][(i-days_L):i],df_this["Benchmark"][(i-days_L):i]) 428 | df_this.iloc[[i],[3]] = cov_matrix[0,1]/cov_matrix[1,1] 429 | for i in range(days_S, len(df_this)): 430 | cov_matrix = np.cov(df_this["Strategy"][(i-days_S):i],df_this["Benchmark"][(i-days_S):i]) 431 | df_this.iloc[[i],[2]] = cov_matrix[0,1]/cov_matrix[1,1] 432 | df_this.drop(["Benchmark","Strategy"],1,inplace = True) 433 | df_this["Empty"] = 0 434 | 435 | # Drawing charts 436 | plt.figure() 437 | ax = df_this.plot(color = ["#CCCCCC","#428BCA"]) 438 | fig = ax.get_figure() 439 | plt.xticks(rotation = 0,ha = 'center') 440 | plt.xlabel("") 441 | ax.legend(["Beta6mo","Beta12mo"],prop = {'weight':'bold'},frameon=False, loc = "upper left") 442 | ax.xaxis.set_major_formatter(DateFormatter("%b %Y")) 443 | plt.axhline(y = 0, color = 'grey') 444 | plt.setp(ax.spines.values(), color='grey') 445 | plt.setp([ax.get_xticklines(), ax.get_yticklines()], color='grey') 446 | plt.xlabel("") 447 | plt.ylabel("") 448 | ax.spines['right'].set_visible(False) 449 | ax.spines['top'].set_visible(False) 450 | ax.yaxis.grid(True) 451 | fig.set_size_inches(width, height) 452 | fig.savefig(self.outdir + "/" + name, dpi = 200, bbox_inches='tight') 453 | plt.cla() 454 | plt.clf() 455 | plt.close('all') 456 | return True 457 | 458 | def rolling_sharpe(self, name = "rolling-sharpe-ratio(6-month).png",width = 11.5, height = 2.5): 459 | if self.is_drawable: 460 | # Prepare the dataset to be used for drawing charts 461 | days_S = 126 462 | days_in_one_year = 252 463 | if len(set(self.df.index.date)) > days_S: 464 | df_this = self.df.copy() 465 | df_this.drop("Benchmark",1,inplace = True) 466 | df_this = df_this.groupby([df_this.index.date]).apply(lambda x: x.tail(1)) 467 | df_this.index = df_this.index.droplevel(1) 468 | ret_strategy = np.array([self.initStrategyValue] + df_this["Strategy"].tolist()) 469 | ret_strategy = ret_strategy[1:]/ret_strategy[:-1] - 1 470 | df_this["Strategy"] = ret_strategy*100 471 | df_this["SharpeRatio"] = float("nan") 472 | for i in range(days_S, len(df_this)): 473 | tmp_ret = np.mean(df_this["Strategy"][(i-days_S):i]) * days_in_one_year 474 | tmp_std = max(np.std(df_this["Strategy"][(i-days_S):i]) * math.sqrt(days_in_one_year),0.0001) 475 | df_this.iloc[[i],[1]] = tmp_ret/tmp_std 476 | df_this.drop("Strategy",1,inplace = True) 477 | df_this["mean"] = np.mean(df_this["SharpeRatio"]) 478 | 479 | # Drawing charts 480 | plt.figure() 481 | ax = df_this["SharpeRatio"].plot(color = "#F5AE29") 482 | ax = df_this["mean"].plot(color = "red", linestyle = "dashed") 483 | fig = ax.get_figure() 484 | plt.xticks(rotation = 0,ha = 'center') 485 | plt.xlabel("") 486 | plt.legend(["SharpeRatio","mean"],prop = {'weight':'bold'},frameon=False, loc = "upper left") 487 | ax.xaxis.set_major_formatter(DateFormatter("%b %Y")) 488 | plt.axhline(y = 0, color = 'grey') 489 | plt.setp(ax.spines.values(), color='grey') 490 | plt.setp([ax.get_xticklines(), ax.get_yticklines()], color='grey') 491 | plt.ylabel("") 492 | plt.xlabel("") 493 | ax.spines['right'].set_visible(False) 494 | ax.spines['top'].set_visible(False) 495 | ax.yaxis.grid(True) 496 | fig.set_size_inches(width, height) 497 | fig.savefig(self.outdir + "/" + name, dpi = 200, bbox_inches='tight') 498 | plt.cla() 499 | plt.clf() 500 | plt.close('all') 501 | return True 502 | 503 | def net_holdings(self, name = "net-holdings.png",width = 11.5, height = 2.5): 504 | if self.is_drawable: 505 | # Prepare the dataset to be used for drawing charts 506 | df_this = self.df_cash.copy() 507 | df_this["Strategy"] = df_this["Value"]/df_this["Strategy"]*100 508 | df_this.drop(df_this.columns[[1,2]],1,inplace = True) 509 | df_this = df_this.groupby([df_this.index.date,df_this.index.hour,df_this.index.minute], as_index = False).apply(lambda x: x.tail(1)) 510 | df_this.index = df_this.index.droplevel(0) 511 | 512 | # Drawing charts 513 | plt.figure() 514 | ax = df_this.plot(color = "white", alpha=0) 515 | ax.fill_between(df_this.index.values,0,df_this['Strategy'], where = 0df_this['Strategy'], color = "grey",step = "pre") 517 | fig = ax.get_figure() 518 | plt.xticks(rotation = 0,ha = 'center') 519 | plt.xlabel("") 520 | ax.xaxis.set_major_formatter(DateFormatter("%b %Y")) 521 | plt.axhline(y = 0, color = 'grey') 522 | ax.legend_.remove() 523 | plt.setp(ax.spines.values(), color='grey') 524 | plt.setp([ax.get_xticklines(), ax.get_yticklines()], color='grey') 525 | plt.ylabel("") 526 | plt.xlabel("") 527 | ax.spines['right'].set_visible(False) 528 | ax.spines['top'].set_visible(False) 529 | ax.yaxis.grid(True) 530 | fig.set_size_inches(width, height) 531 | fig.savefig(self.outdir + "/" + name, dpi = 200, bbox_inches='tight') 532 | plt.cla() 533 | plt.clf() 534 | plt.close('all') 535 | return True 536 | 537 | def leverage(self, name = "leverage.png",width = 11.5, height = 2.5): 538 | if self.is_drawable: 539 | # Prepare the dataset to be used for drawing charts 540 | df_this = self.df_cash.copy() 541 | df_this["Strategy"] = abs(df_this["Value"]/df_this["Strategy"]*100) 542 | df_this.drop(df_this.columns[[1,2]],1,inplace = True) 543 | df_this = df_this.groupby([df_this.index.date,df_this.index.hour,df_this.index.minute], as_index = False).apply(lambda x: x.tail(1)) 544 | df_this.index = df_this.index.droplevel(0) 545 | 546 | # Drawing charts 547 | plt.figure() 548 | ax = df_this.plot(color = "#F5AE29") 549 | ax.fill_between(df_this.index.values,0,df_this['Strategy'], color = "#F5AE29",step = "pre") 550 | fig = ax.get_figure() 551 | plt.xticks(rotation = 0,ha = 'center') 552 | plt.xlabel("") 553 | ax.xaxis.set_major_formatter(DateFormatter("%b %Y")) 554 | plt.axhline(y = 0, color = 'grey') 555 | ax.legend_.remove() 556 | plt.setp(ax.spines.values(), color='grey') 557 | plt.setp([ax.get_xticklines(), ax.get_yticklines()], color='grey') 558 | plt.ylabel("") 559 | plt.xlabel("") 560 | ax.spines['right'].set_visible(False) 561 | ax.spines['top'].set_visible(False) 562 | ax.grid() 563 | fig.set_size_inches(width, height) 564 | fig.savefig(self.outdir + "/" + name, dpi = 200, bbox_inches='tight') 565 | plt.cla() 566 | plt.clf() 567 | plt.close('all') 568 | return True 569 | 570 | def asset_allocation(self,width = 3.5*2, height = 2.5*2): 571 | if self.is_drawable: 572 | df_this = self.df.copy() 573 | df_this.drop("Benchmark",1,inplace = True) 574 | df_values = pd.DataFrame() 575 | df_values["Value"] = [x["Value"] for x in self.orders.values()] 576 | df_values["Symbol"] = [x["Symbol"]["Value"] for x in self.orders.values()] 577 | df_values["Type"] = [x["SecurityType"] for x in self.orders.values()] 578 | df_values = df_values.set_index([[datetime.strptime(x["Time"][0:19], '%Y-%m-%dT%H:%M:%S') for x in self.orders.values()]]) 579 | timeBegin = df_this.index[0] 580 | timeEnd = df_this.index[-1] 581 | timeDuration = (timeEnd - timeBegin).total_seconds() 582 | df_cash_tmp = df_values.copy() 583 | df_cash_tmp["Value"] = -df_cash_tmp["Value"] 584 | df_cash_tmp["Symbol"] = "CASH" 585 | df_cash_tmp["Type"] = 0 586 | if timeBegin in df_cash_tmp.index: 587 | df_cash_tmp.loc[timeBegin-timedelta(seconds = 1)] = [df_this["Strategy"][0], "CASH", 0] 588 | timeBegin = timeBegin-timedelta(seconds = 1) 589 | else: 590 | df_cash_tmp.loc[timeBegin] = [df_this["Strategy"][0], "CASH", 0] 591 | df_values = df_values.append(df_cash_tmp) 592 | df_values.sort_index(inplace = True) 593 | self.df_values = df_values 594 | SecurityTypeName = ['Cash','Equity', 'Option', 'Commodity', 'Forex', 'Future', 'Cfd', 'Crypto'] 595 | asset_alloc = [] 596 | for SecurityType in range(0,7+1): 597 | df_tmp = df_values.where(df_values["Type"] == SecurityType).iloc[:,0].copy() 598 | df_tmp = df_tmp.groupby(df_tmp.index).sum().cumsum() 599 | list_timestamp = list(df_tmp.index) 600 | list_timestamp.append(timeEnd) 601 | timeWeightedValue = sum([(list_timestamp[i+1] - list_timestamp[i]).total_seconds()/timeDuration*df_tmp[i] for i in range(len(df_tmp))]) 602 | asset_alloc.append(timeWeightedValue) 603 | df_pie = pd.DataFrame() 604 | df_pie["Value"] = asset_alloc 605 | # df_pie["Weight"] = [round(x/sum(df_pie["Value"])*100,1) for x in df_pie["Value"]] 606 | df_pie["AbsWeight"] = [round(abs(x)/sum(abs(df_pie["Value"]))*100,1) for x in df_pie["Value"]] 607 | df_pie["Labels"] = SecurityTypeName 608 | df_pie = df_pie.where(df_pie["Value"] != 0).dropna(axis = 0, how = "any") 609 | if len([x for x in df_pie["AbsWeight"] if x < 5]) > 1: 610 | df_pie["Labels"] = [ df_pie["Labels"].iloc[i] if df_pie["AbsWeight"].iloc[i] >= 5 else "Others" for i in range(len(df_pie)) ] 611 | df_pie = df_pie.groupby(by = "Labels").sum() 612 | df_pie.reset_index(inplace = True) 613 | df_pie.sort_values(by = ['AbsWeight','Value'],ascending = False, inplace = True) 614 | df_pie["Labels"] = [str(round(df_pie["AbsWeight"].iloc[i],1)) + "%\n" + df_pie["Labels"].iloc[i] 615 | if df_pie["Value"].iloc[i] >= 0 else "(" + str(round(df_pie["AbsWeight"].iloc[i],1)) + "%)\n" + df_pie["Labels"].iloc[i] 616 | for i in range(len(df_pie))] 617 | df_pie["Value"] = abs(df_pie["Value"]) 618 | colors = ['#FFE5CC', '#FFCC99', '#FFB266', '#FF9933', '#FF8000', '#CC6600','#994C00','#990000'] 619 | 620 | fig = plt.figure() 621 | patches, texts, autotexts = plt.pie(df_pie["Value"], labels=df_pie["Labels"], colors=colors, autopct="", startangle=90, labeldistance = 0.5) 622 | for x in texts: 623 | x.set_fontsize(12) 624 | x.set_fontweight("bold") 625 | for x in autotexts: 626 | x.set_fontsize(12) 627 | x.set_fontweight("bold") 628 | plt.axis('equal') 629 | fig.set_size_inches(width, height) 630 | fig.savefig(self.outdir + "/asset-allocation-all.png", dpi = 200, bbox_inches='tight') 631 | plt.cla() 632 | plt.clf() 633 | plt.close('all') 634 | 635 | for SecurityType in range(1,7+1): 636 | df_tmp = df_values.where(df_values["Type"] == SecurityType).copy() 637 | asset_symbols = list(set(df_tmp["Symbol"].dropna(axis = 0))) 638 | if asset_symbols: 639 | asset_alloc = [] 640 | for sym in asset_symbols: 641 | df_tmp2 = df_tmp.where(df_tmp["Symbol"]==sym).iloc[:,0].copy() 642 | df_tmp2 = df_tmp2.groupby(df_tmp2.index).sum().cumsum() 643 | list_timestamp = list(df_tmp2.index) 644 | list_timestamp.append(timeEnd) 645 | timeWeightedValue = sum([(list_timestamp[i+1] - list_timestamp[i]).total_seconds()/timeDuration*df_tmp2[i] for i in range(len(df_tmp2))]) 646 | asset_alloc.append(timeWeightedValue) 647 | asset_symbols = [asset_symbols[i] if i < 7 else "Others" for i in range(len(asset_symbols))] 648 | if len(asset_alloc) > 7: 649 | asset_alloc = list(asset_alloc[0:7] + [sum(asset_alloc[7:])]) 650 | asset_symbols = asset_symbols[0:8] 651 | if not sum([abs(x) for x in asset_alloc]): 652 | continue 653 | df_pie = pd.DataFrame() 654 | df_pie["Value"] = asset_alloc 655 | # df_pie["Weight"] = [round(x/sum(df_pie["Value"])*100,1) for x in df_pie["Value"]] 656 | df_pie["AbsWeight"] = [round(abs(x)/sum(abs(df_pie["Value"]))*100,1) for x in df_pie["Value"]] 657 | df_pie["Labels"] = asset_symbols 658 | if len([x for x in df_pie["AbsWeight"] if x < 5]) > 1: 659 | df_pie["Labels"] = [ df_pie["Labels"].iloc[i] if df_pie["AbsWeight"].iloc[i] >= 5 else "Others" for i in range(len(df_pie)) ] 660 | df_pie = df_pie.groupby(by = "Labels").sum() 661 | df_pie.reset_index(inplace = True) 662 | df_pie.sort_values(by = ['AbsWeight','Value'],ascending = False, inplace = True) 663 | df_pie["Labels"] = [str(round(df_pie["AbsWeight"].iloc[i],1)) + "%\n" + df_pie["Labels"].iloc[i] 664 | if df_pie["Value"].iloc[i] >= 0 else "(" + str(round(df_pie["AbsWeight"].iloc[i],1)) + "%)\n" + df_pie["Labels"].iloc[i] 665 | for i in range(len(df_pie))] 666 | df_pie = df_pie.where(df_pie["Value"] != 0).dropna(axis = 0, how = "any") 667 | df_pie["Value"] = abs(df_pie["Value"]) 668 | colors = ['#FFE5CC', '#FFCC99', '#FFB266', '#FF9933', '#FF8000', '#CC6600','#994C00','#990000'] 669 | 670 | fig = plt.figure() 671 | patches, texts, autotexts = plt.pie(df_pie["Value"], labels=df_pie["Labels"], colors=colors, autopct="", startangle=90, labeldistance = 0.6) 672 | for x in texts: 673 | x.set_fontsize(12) 674 | x.set_fontweight("bold") 675 | for x in autotexts: 676 | x.set_fontsize(12) 677 | x.set_fontweight("bold") 678 | plt.axis('equal') 679 | fig.set_size_inches(width, height) 680 | fig.savefig(self.outdir + "/asset-allocation-"+SecurityTypeName[SecurityType].lower()+".png", dpi = 200, bbox_inches='tight') 681 | plt.cla() 682 | plt.clf() 683 | plt.close('all') 684 | return True 685 | 686 | def output_json(self, name = "strategy-statistics.json"): 687 | if self.is_drawable and "TotalPerformance" in self.data: 688 | SignificantPeriod = 1 if (self.df.index[-1] - self.df.index[0]).days/365 > 5 else 0 689 | SignificantTrading = 1 if len(self.orders) >= 100 else 0 690 | Diversified = 1 if len(set(self.df_values["Symbol"])) > 7 else 0 691 | RiskControl = 1 if self.data["TotalPerformance"] and self.data["TotalPerformance"]["PortfolioStatistics"]["Beta"] < 0.5 else 0 692 | SecurityTypeName = ['Equity', 'Option', 'Commodity', 'Forex', 'Future', 'Cfd', 'Crypto'] 693 | Markets = [SecurityTypeName[x-1] for x in list(set(self.df_values["Type"])) if x > 0] 694 | 695 | CAGR = self.data["TotalPerformance"]["PortfolioStatistics"]["CompoundingAnnualReturn"] if self.data["TotalPerformance"] else 0 696 | Drawdown = self.data["TotalPerformance"]["PortfolioStatistics"]["Drawdown"] if self.data["TotalPerformance"] else 0 697 | SharpeRatio = self.data["TotalPerformance"]["PortfolioStatistics"]["SharpeRatio"] if self.data["TotalPerformance"] else 0 698 | InformationRatio = self.data["TotalPerformance"]["PortfolioStatistics"]["InformationRatio"] if self.data["TotalPerformance"] else 0 699 | TradesPerDay = len(self.orders) / max( (self.df.index[-1] - self.df.index[0]).days , 1) 700 | 701 | res = {"Key Characteristics": [("Significant Period", SignificantPeriod), 702 | ("Significant Trading", SignificantTrading), 703 | ("Diversified", Diversified), 704 | ("Risk Control", RiskControl), 705 | ("Markets", Markets)], 706 | "Key Statistics":[("CAGR", str(round(CAGR*100,2)) + "%"), 707 | ("Drawdown", str(round(Drawdown*100,2)) + "%"), 708 | ("Sharpe Ratio", round(SharpeRatio,3)), 709 | ("Information Ratio", round(InformationRatio,3)), 710 | ("Trades Per Day", round(TradesPerDay,6))]} 711 | 712 | else: 713 | res = {"Key Characteristics": [("Significant Period", 0), 714 | ("Significant Trading", 0), 715 | ("Diversified", 0), 716 | ("Risk Control", 0), 717 | ("Markets", [])], 718 | "Key Statistics":[("CAGR", 0), 719 | ("Drawdown", 0), 720 | ("Sharpe Ratio", 0), 721 | ("Information Ratio", 0), 722 | ("Trades Per Day", 0)]} 723 | with open(self.outdir + "/" + name, 'w+') as f: 724 | json.dump(res, f, ensure_ascii=False) 725 | return True 726 | 727 | def genearte_report(self): 728 | self.cumulative_return() 729 | self.daily_returns() 730 | self.drawdown() 731 | self.monthly_returns() 732 | self.annual_returns() 733 | self.monthly_return_distribution() 734 | self.crisis_events() 735 | self.rolling_beta() 736 | self.rolling_sharpe() 737 | self.net_holdings() 738 | self.leverage() 739 | self.asset_allocation() 740 | self.output_json() 741 | GenerateHTML.GenerateHTMLReport(self.outdir) 742 | 743 | #Usage 744 | lrc = LeanReportCreator("C:/Users/Jack Simonson/36546c701c0d07496c8f7160a7298b68.json") 745 | lrc.genearte_report() 746 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Lean-Report-Creator 2 | 3 | This project has been archived and is no longer maintained. 4 | 5 | The new version is available in LEAN. 6 | https://github.com/QuantConnect/Lean/tree/master/Report 7 | -------------------------------------------------------------------------------- /outputs/annual-returns.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/annual-returns.png -------------------------------------------------------------------------------- /outputs/asset-allocation-all.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/asset-allocation-all.png -------------------------------------------------------------------------------- /outputs/asset-allocation-equity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/asset-allocation-equity.png -------------------------------------------------------------------------------- /outputs/crisis-2009q1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/crisis-2009q1.png -------------------------------------------------------------------------------- /outputs/crisis-2009q2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/crisis-2009q2.png -------------------------------------------------------------------------------- /outputs/crisis-9-11.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/crisis-9-11.png -------------------------------------------------------------------------------- /outputs/crisis-aug07.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/crisis-aug07.png -------------------------------------------------------------------------------- /outputs/crisis-dotcom.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/crisis-dotcom.png -------------------------------------------------------------------------------- /outputs/crisis-flash-crash.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/crisis-flash-crash.png -------------------------------------------------------------------------------- /outputs/crisis-fukushima-melt-down-2011.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/crisis-fukushima-melt-down-2011.png -------------------------------------------------------------------------------- /outputs/crisis-gfc-crash.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/crisis-gfc-crash.png -------------------------------------------------------------------------------- /outputs/crisis-lehman-brothers.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/crisis-lehman-brothers.png -------------------------------------------------------------------------------- /outputs/crisis-low-volatility-bull-market.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/crisis-low-volatility-bull-market.png -------------------------------------------------------------------------------- /outputs/crisis-mar08.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/crisis-mar08.png -------------------------------------------------------------------------------- /outputs/crisis-recovery.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/crisis-recovery.png -------------------------------------------------------------------------------- /outputs/crisis-sept08.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/crisis-sept08.png -------------------------------------------------------------------------------- /outputs/crisis-us-downgrade-european-debt-crisis.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/crisis-us-downgrade-european-debt-crisis.png -------------------------------------------------------------------------------- /outputs/crisis-us-housing-bubble-2003.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/crisis-us-housing-bubble-2003.png -------------------------------------------------------------------------------- /outputs/cumulative-return.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/cumulative-return.png -------------------------------------------------------------------------------- /outputs/daily-returns.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/daily-returns.png -------------------------------------------------------------------------------- /outputs/distribution-of-monthly-returns.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/distribution-of-monthly-returns.png -------------------------------------------------------------------------------- /outputs/drawdowns.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/drawdowns.png -------------------------------------------------------------------------------- /outputs/leverage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/leverage.png -------------------------------------------------------------------------------- /outputs/monthly-returns.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/monthly-returns.png -------------------------------------------------------------------------------- /outputs/net-holdings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/net-holdings.png -------------------------------------------------------------------------------- /outputs/rolling-portfolio-beta-to-equity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/rolling-portfolio-beta-to-equity.png -------------------------------------------------------------------------------- /outputs/rolling-sharpe-ratio(6-month).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantConnect/LeanReportCreator/98200b1a32f433d5398d58fbb96a59bcdbd73a8a/outputs/rolling-sharpe-ratio(6-month).png -------------------------------------------------------------------------------- /outputs/strategy-statistics.json: -------------------------------------------------------------------------------- 1 | {"Key Characteristics": [["Significant Period", 1], ["Significant Trading", 1], ["Diversified", 0], ["Risk Control", 1], ["Markets", ["Equity"]]], "Key Statistics": [["CAGR", "24.06%"], ["Drawdown", "12.7%"], ["Sharpe Ratio", 1.783], ["Information Ratio", 0.701], ["Trades Per Day", 2.367396]]} --------------------------------------------------------------------------------