guohanghui commited on
Commit
4144d57
·
verified ·
1 Parent(s): 869c823

Upload 103 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. pyfolio/mcp_output/README_MCP.md +202 -0
  3. pyfolio/mcp_output/analysis.json +259 -0
  4. pyfolio/mcp_output/env_info.json +15 -0
  5. pyfolio/mcp_output/mcp_logs/llm_statistics.json +11 -0
  6. pyfolio/mcp_output/mcp_logs/run_log.json +96 -0
  7. pyfolio/mcp_output/mcp_plugin/__init__.py +0 -0
  8. pyfolio/mcp_output/mcp_plugin/__pycache__/adapter.cpython-310.pyc +0 -0
  9. pyfolio/mcp_output/mcp_plugin/__pycache__/mcp_service.cpython-310.pyc +0 -0
  10. pyfolio/mcp_output/mcp_plugin/adapter.py +326 -0
  11. pyfolio/mcp_output/mcp_plugin/main.py +13 -0
  12. pyfolio/mcp_output/mcp_plugin/mcp_service.py +179 -0
  13. pyfolio/mcp_output/requirements.txt +12 -0
  14. pyfolio/mcp_output/simple_revise_error_analysis.json +36 -0
  15. pyfolio/mcp_output/start_mcp.py +39 -0
  16. pyfolio/mcp_output/tests_mcp/test_mcp_basic.py +49 -0
  17. pyfolio/mcp_output/tests_smoke/test_smoke.py +29 -0
  18. pyfolio/source/.gitattributes +1 -0
  19. pyfolio/source/.github/ISSUE_TEMPLATE.md +21 -0
  20. pyfolio/source/.gitignore +63 -0
  21. pyfolio/source/.travis.yml +54 -0
  22. pyfolio/source/LICENSE +202 -0
  23. pyfolio/source/MANIFEST.in +3 -0
  24. pyfolio/source/README.md +81 -0
  25. pyfolio/source/WHATSNEW.md +310 -0
  26. pyfolio/source/__init__.py +4 -0
  27. pyfolio/source/build_and_deploy_docs.sh +7 -0
  28. pyfolio/source/conda/bld.bat +8 -0
  29. pyfolio/source/conda/build.sh +9 -0
  30. pyfolio/source/conda/meta.yaml +43 -0
  31. pyfolio/source/docs/convert_nbs_to_md.sh +10 -0
  32. pyfolio/source/docs/example_tear_0.png +0 -0
  33. pyfolio/source/docs/example_tear_1.png +3 -0
  34. pyfolio/source/docs/extra.css +4 -0
  35. pyfolio/source/docs/index.md +81 -0
  36. pyfolio/source/docs/notebooks/fama_french_benchmark.ipynb +0 -0
  37. pyfolio/source/docs/notebooks/full_tear_sheet_example.ipynb +0 -0
  38. pyfolio/source/docs/notebooks/round_trip_tear_sheet_example.ipynb +0 -0
  39. pyfolio/source/docs/notebooks/sector_mappings_example.ipynb +0 -0
  40. pyfolio/source/docs/notebooks/single_stock_example.ipynb +0 -0
  41. pyfolio/source/docs/notebooks/slippage_example.ipynb +0 -0
  42. pyfolio/source/docs/notebooks/zipline_algo_example.ipynb +0 -0
  43. pyfolio/source/docs/simple_tear_0.png +0 -0
  44. pyfolio/source/docs/simple_tear_1.png +3 -0
  45. pyfolio/source/docs/whatsnew.md +310 -0
  46. pyfolio/source/mkdocs.yml +15 -0
  47. pyfolio/source/pyfolio/__init__.py +19 -0
  48. pyfolio/source/pyfolio/__pycache__/__init__.cpython-310.pyc +0 -0
  49. pyfolio/source/pyfolio/__pycache__/utils.cpython-310.pyc +0 -0
  50. pyfolio/source/pyfolio/_seaborn.py +18 -0
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ pyfolio/source/docs/example_tear_1.png filter=lfs diff=lfs merge=lfs -text
37
+ pyfolio/source/docs/simple_tear_1.png filter=lfs diff=lfs merge=lfs -text
38
+ pyfolio/source/pyfolio/examples/pydata_stack-4-finance.jpg filter=lfs diff=lfs merge=lfs -text
pyfolio/mcp_output/README_MCP.md ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MCP Plugin: PyFolio
2
+
3
+ ## Overview
4
+
5
+ PyFolio is a Python library designed for performance and risk analysis of financial portfolios. Developed by Quantopian Inc., it provides tools to evaluate trading strategies through visualizations and statistical metrics. PyFolio generates "tear sheets," which are comprehensive reports containing visualizations and metrics that help assess various aspects of portfolio performance.
6
+
7
+ The library integrates seamlessly with the Zipline backtesting library but can also be used independently with any source of portfolio data. PyFolio is modular, allowing users to focus on specific aspects of portfolio analysis or generate comprehensive reports.
8
+
9
+ ## Features
10
+
11
+ - **Tear Sheet Generation**: Create detailed reports for portfolio performance analysis.
12
+ - **Visualization Tools**: Generate plots for returns, drawdowns, exposures, and more.
13
+ - **Performance Attribution**: Decompose portfolio returns into factor components.
14
+ - **Round Trip Analysis**: Evaluate completed trades and their profitability.
15
+ - **Capacity Analysis**: Assess the scalability of trading strategies.
16
+ - **Integration**: Works with Zipline, Empyrical, and custom data sources.
17
+
18
+ ## Installation
19
+
20
+ To install PyFolio, ensure you have Python 3.6 or later installed. You can install the library using pip:
21
+
22
+ ```bash
23
+ pip install pyfolio
24
+ ```
25
+
26
+ Alternatively, you can clone the repository and install it manually:
27
+
28
+ ```bash
29
+ git clone https://github.com/quantopian/pyfolio.git
30
+ cd pyfolio
31
+ pip install .
32
+ ```
33
+
34
+ ## Dependencies
35
+
36
+ PyFolio requires the following Python libraries:
37
+
38
+ - **Required**:
39
+ - `numpy`
40
+ - `pandas`
41
+ - `matplotlib`
42
+ - `seaborn`
43
+ - `scipy`
44
+ - `statsmodels`
45
+ - **Optional**:
46
+ - `jupyter` (for interactive notebooks)
47
+ - `pytest` (for testing)
48
+
49
+ Ensure these dependencies are installed before using PyFolio.
50
+
51
+ ## Usage
52
+
53
+ PyFolio provides several methods for generating tear sheets and visualizations. Below are examples of common usage scenarios:
54
+
55
+ ### Basic Tear Sheet Generation
56
+
57
+ To generate a full tear sheet for portfolio analysis:
58
+
59
+ ```python
60
+ import pyfolio as pf
61
+
62
+ # Example: Generate a tear sheet using returns data
63
+ pf.create_full_tear_sheet(returns)
64
+ ```
65
+
66
+ ### Specialized Tear Sheets
67
+
68
+ PyFolio allows you to generate specific tear sheets for focused analysis:
69
+
70
+ - **Returns Analysis**:
71
+ ```python
72
+ pf.create_returns_tear_sheet(returns)
73
+ ```
74
+ - **Position Analysis**:
75
+ ```python
76
+ pf.create_position_tear_sheet(positions)
77
+ ```
78
+ - **Transaction Analysis**:
79
+ ```python
80
+ pf.create_txn_tear_sheet(transactions)
81
+ ```
82
+ - **Round Trip Analysis**:
83
+ ```python
84
+ pf.create_round_trip_tear_sheet(returns, positions, transactions)
85
+ ```
86
+ - **Capacity Analysis**:
87
+ ```python
88
+ pf.create_capacity_tear_sheet(returns, positions)
89
+ ```
90
+ - **Performance Attribution**:
91
+ ```python
92
+ pf.create_perf_attrib_tear_sheet(returns, factor_returns)
93
+ ```
94
+
95
+ ### Integration with Zipline
96
+
97
+ PyFolio integrates seamlessly with Zipline. You can extract portfolio data from Zipline and use it with PyFolio:
98
+
99
+ ```python
100
+ from pyfolio.utils import extract_rets_pos_txn_from_zipline
101
+
102
+ returns, positions, transactions = extract_rets_pos_txn_from_zipline(zipline_results)
103
+ pf.create_full_tear_sheet(returns, positions=positions, transactions=transactions)
104
+ ```
105
+
106
+ ### Visualization Functions
107
+
108
+ PyFolio includes standalone plotting functions for specific visualizations:
109
+
110
+ - Plot returns:
111
+ ```python
112
+ pf.plot_returns(returns)
113
+ ```
114
+ - Plot rolling returns:
115
+ ```python
116
+ pf.plot_rolling_returns(returns, factor_returns)
117
+ ```
118
+ - Plot drawdown periods:
119
+ ```python
120
+ pf.plot_drawdown_periods(returns)
121
+ ```
122
+ - Plot monthly returns heatmap:
123
+ ```python
124
+ pf.plot_monthly_returns_heatmap(returns)
125
+ ```
126
+
127
+ ## Available Endpoints
128
+
129
+ ### Tear Sheet Functions
130
+
131
+ - `create_full_tear_sheet`
132
+ - `create_simple_tear_sheet`
133
+ - `create_returns_tear_sheet`
134
+ - `create_position_tear_sheet`
135
+ - `create_txn_tear_sheet`
136
+ - `create_round_trip_tear_sheet`
137
+ - `create_interesting_times_tear_sheet`
138
+ - `create_capacity_tear_sheet`
139
+ - `create_perf_attrib_tear_sheet`
140
+
141
+ ### Visualization Functions
142
+
143
+ - `plot_returns`
144
+ - `plot_rolling_returns`
145
+ - `plot_drawdown_periods`
146
+ - `plot_monthly_returns_heatmap`
147
+ - `plot_holdings`
148
+ - `plot_position_exposures`
149
+ - `plot_turnover`
150
+
151
+ ### Utility Functions
152
+
153
+ - `extract_rets_pos_txn_from_zipline`
154
+ - `get_clean_factor_and_forward_returns`
155
+
156
+ ## Notes and Troubleshooting
157
+
158
+ ### Common Issues
159
+
160
+ 1. **Missing Dependencies**:
161
+ Ensure all required libraries are installed. Use `pip install` to install missing dependencies.
162
+
163
+ 2. **Data Format Errors**:
164
+ PyFolio expects input data in specific formats (e.g., pandas DataFrames). Ensure your data conforms to these requirements.
165
+
166
+ 3. **Visualization Errors**:
167
+ If plots fail to render, check your matplotlib and seaborn installations. Update them to the latest versions if necessary.
168
+
169
+ 4. **Integration with Zipline**:
170
+ Ensure Zipline results are correctly formatted before extracting data using `extract_rets_pos_txn_from_zipline`.
171
+
172
+ ### Debugging Tips
173
+
174
+ - Use PyFolio's built-in logging to identify issues:
175
+ ```python
176
+ import logging
177
+ logging.basicConfig(level=logging.DEBUG)
178
+ ```
179
+ - Validate input data using pandas functions (e.g., `df.info()` or `df.head()`).
180
+
181
+ ### Reporting Issues
182
+
183
+ If you encounter bugs or have feature requests, please open an issue on the PyFolio GitHub repository:
184
+ [https://github.com/quantopian/pyfolio/issues](https://github.com/quantopian/pyfolio/issues)
185
+
186
+ ## Development and Contributions
187
+
188
+ PyFolio is an open-source project. Contributions are welcome! To contribute:
189
+
190
+ 1. Fork the repository.
191
+ 2. Create a new branch for your feature or bug fix.
192
+ 3. Submit a pull request with a detailed description of your changes.
193
+
194
+ For development guidelines, refer to the `CONTRIBUTING.md` file in the repository.
195
+
196
+ ## License
197
+
198
+ PyFolio is licensed under the Apache License 2.0. See the `LICENSE` file for details.
199
+
200
+ ---
201
+
202
+ For more information, visit the [PyFolio GitHub repository](https://github.com/quantopian/pyfolio).
pyfolio/mcp_output/analysis.json ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "summary": {
3
+ "repository_url": "https://github.com/quantopian/pyfolio",
4
+ "summary": "Imported via zip fallback, file count: 35",
5
+ "file_tree": {
6
+ ".github/ISSUE_TEMPLATE.md": {
7
+ "size": 355
8
+ },
9
+ ".travis.yml": {
10
+ "size": 1335
11
+ },
12
+ "README.md": {
13
+ "size": 3296
14
+ },
15
+ "WHATSNEW.md": {
16
+ "size": 13819
17
+ },
18
+ "conda/meta.yaml": {
19
+ "size": 976
20
+ },
21
+ "docs/index.md": {
22
+ "size": 12
23
+ },
24
+ "docs/whatsnew.md": {
25
+ "size": 14
26
+ },
27
+ "mkdocs.yml": {
28
+ "size": 497
29
+ },
30
+ "pyfolio/__init__.py": {
31
+ "size": 481
32
+ },
33
+ "pyfolio/_seaborn.py": {
34
+ "size": 446
35
+ },
36
+ "pyfolio/_version.py": {
37
+ "size": 15800
38
+ },
39
+ "pyfolio/capacity.py": {
40
+ "size": 9616
41
+ },
42
+ "pyfolio/deprecate.py": {
43
+ "size": 1499
44
+ },
45
+ "pyfolio/interesting_periods.py": {
46
+ "size": 2904
47
+ },
48
+ "pyfolio/ipycompat.py": {
49
+ "size": 581
50
+ },
51
+ "pyfolio/perf_attrib.py": {
52
+ "size": 22416
53
+ },
54
+ "pyfolio/plotting.py": {
55
+ "size": 63276
56
+ },
57
+ "pyfolio/pos.py": {
58
+ "size": 7172
59
+ },
60
+ "pyfolio/round_trips.py": {
61
+ "size": 15178
62
+ },
63
+ "pyfolio/tears.py": {
64
+ "size": 47386
65
+ },
66
+ "pyfolio/tests/__init__.py": {
67
+ "size": 0
68
+ },
69
+ "pyfolio/tests/test_capacity.py": {
70
+ "size": 5477
71
+ },
72
+ "pyfolio/tests/test_nbs.py": {
73
+ "size": 666
74
+ },
75
+ "pyfolio/tests/test_perf_attrib.py": {
76
+ "size": 18611
77
+ },
78
+ "pyfolio/tests/test_pos.py": {
79
+ "size": 6850
80
+ },
81
+ "pyfolio/tests/test_round_trips.py": {
82
+ "size": 7911
83
+ },
84
+ "pyfolio/tests/test_tears.py": {
85
+ "size": 4911
86
+ },
87
+ "pyfolio/tests/test_timeseries.py": {
88
+ "size": 12272
89
+ },
90
+ "pyfolio/tests/test_txn.py": {
91
+ "size": 3215
92
+ },
93
+ "pyfolio/timeseries.py": {
94
+ "size": 37350
95
+ },
96
+ "pyfolio/txn.py": {
97
+ "size": 6457
98
+ },
99
+ "pyfolio/utils.py": {
100
+ "size": 16144
101
+ },
102
+ "setup.cfg": {
103
+ "size": 352
104
+ },
105
+ "setup.py": {
106
+ "size": 2636
107
+ },
108
+ "versioneer.py": {
109
+ "size": 62477
110
+ }
111
+ },
112
+ "processed_by": "zip_fallback",
113
+ "success": true
114
+ },
115
+ "structure": {
116
+ "packages": [
117
+ "source.pyfolio",
118
+ "source.pyfolio.tests"
119
+ ]
120
+ },
121
+ "dependencies": {
122
+ "has_environment_yml": false,
123
+ "has_requirements_txt": false,
124
+ "pyproject": false,
125
+ "setup_cfg": true,
126
+ "setup_py": true
127
+ },
128
+ "entry_points": {
129
+ "imports": [],
130
+ "cli": [],
131
+ "modules": []
132
+ },
133
+ "llm_analysis": {
134
+ "core_modules": [
135
+ {
136
+ "package": "source.pyfolio",
137
+ "module": "pyfolio.plotting",
138
+ "functions": [
139
+ "create_returns_tear_sheet",
140
+ "create_position_tear_sheet",
141
+ "create_txn_tear_sheet",
142
+ "show_worst_drawdown_periods",
143
+ "plot_rolling_returns",
144
+ "plot_rolling_beta",
145
+ "plot_rolling_volatility",
146
+ "plot_drawdown_periods",
147
+ "plot_monthly_returns_heatmap",
148
+ "plot_monthly_returns_dist",
149
+ "plot_holdings",
150
+ "plot_sector_allocations"
151
+ ],
152
+ "classes": [],
153
+ "description": "Contains functions for visualizing financial performance metrics and generating tear sheets."
154
+ },
155
+ {
156
+ "package": "source.pyfolio",
157
+ "module": "pyfolio.timeseries",
158
+ "functions": [
159
+ "cum_returns",
160
+ "cum_returns_final",
161
+ "aggregate_returns",
162
+ "annual_return",
163
+ "annual_volatility",
164
+ "sharpe_ratio",
165
+ "sortino_ratio",
166
+ "max_drawdown",
167
+ "alpha_beta",
168
+ "beta",
169
+ "alpha",
170
+ "stability_of_timeseries",
171
+ "tail_ratio",
172
+ "value_at_risk",
173
+ "capture",
174
+ "up_capture",
175
+ "down_capture"
176
+ ],
177
+ "classes": [],
178
+ "description": "Provides utility functions for analyzing time series data related to financial performance."
179
+ },
180
+ {
181
+ "package": "source.pyfolio",
182
+ "module": "pyfolio.tears",
183
+ "functions": [
184
+ "create_full_tear_sheet",
185
+ "create_simple_tear_sheet",
186
+ "create_interesting_periods_tear_sheet"
187
+ ],
188
+ "classes": [],
189
+ "description": "Generates comprehensive tear sheets for analyzing portfolio performance."
190
+ },
191
+ {
192
+ "package": "source.pyfolio",
193
+ "module": "pyfolio.capacity",
194
+ "functions": [
195
+ "compute_max_capacity",
196
+ "compute_capacity"
197
+ ],
198
+ "classes": [],
199
+ "description": "Contains functions for estimating portfolio capacity and liquidity constraints."
200
+ },
201
+ {
202
+ "package": "source.pyfolio",
203
+ "module": "pyfolio.utils",
204
+ "functions": [
205
+ "extract_returns",
206
+ "extract_positions",
207
+ "extract_transactions",
208
+ "extract_benchmark_returns",
209
+ "extract_interesting_periods",
210
+ "extract_sector_allocations"
211
+ ],
212
+ "classes": [],
213
+ "description": "Utility functions for extracting and processing portfolio data."
214
+ }
215
+ ],
216
+ "cli_commands": [],
217
+ "import_strategy": {
218
+ "primary": "import",
219
+ "fallback": "blackbox",
220
+ "confidence": 0.85
221
+ },
222
+ "dependencies": {
223
+ "required": [
224
+ "numpy",
225
+ "pandas",
226
+ "matplotlib",
227
+ "seaborn",
228
+ "scipy",
229
+ "statsmodels"
230
+ ],
231
+ "optional": [
232
+ "jupyter",
233
+ "pytest"
234
+ ]
235
+ },
236
+ "risk_assessment": {
237
+ "import_feasibility": 0.85,
238
+ "intrusiveness_risk": "low",
239
+ "complexity": "medium"
240
+ }
241
+ },
242
+ "deepwiki_analysis": {
243
+ "repo_url": "https://github.com/quantopian/pyfolio",
244
+ "repo_name": "pyfolio",
245
+ "content": "quantopian/pyfolio\nCore Architecture\nTear Sheets\nPerformance and Risk Analysis\nPlotting Functions\nUtility Functions\nSpecialized Analysis Modules\nPosition Analysis\nTransaction Analysis\nRound Trip and Capacity Analysis\nPerformance Attribution\nIntegration with External Systems\nUsage Examples\nSingle Stock Analysis\nZipline Algorithm Analysis\nBayesian Analysis\nSector Analysis and Round Trips\nDevelopment Guide\nInstallation and Setup\nDocumentation\n.travis.yml\nWHATSNEW.md\ndocs/whatsnew.md\npyfolio/__init__.py\nversioneer.py\nPyFolio is a Python library for performance and risk analysis of financial portfolios. Developed by Quantopian Inc., it provides a comprehensive set of tools to evaluate trading strategies through visualizations and statistical metrics. This document provides a high-level overview of PyFolio's architecture, components, and functionality.\nAt its core, PyFolio takes portfolio performance data (such as returns, positions, and transactions) and generates \"tear sheets\" - collections of visualizations and metrics that help assess different aspects of trading strategy performance. PyFolio works seamlessly with theZiplinebacktesting library but can be used independently with any source of portfolio data.\nFor detailed information about specific components, seeCore ArchitectureorSpecialized Analysis Modules.\nSources:setup.py9-21README.md8-20\nSystem Architecture\nPyFolio follows a modular architecture where distinct components work together to process financial data and generate performance visualizations. The system is organized around core analysis modules and a tear sheet generation system that orchestrates the creation of various reports.\nExternal DependenciesCore Componentstears.py (Tear Sheet Generation)plotting.py (Visualization)timeseries.py (Returns Analysis)utils.py (Helper Functions)pos.py (Position Analysis)txn.py (Transaction Analysis)perf_attrib.py (Performance Attribution)round_trips.py (Round Trip Analysis)capacity.py (Strategy Capacity)empyrical (Performance Metrics)pandas (Data Structures)numpy (Numerical Operations)matplotlib (Base Plotting)seaborn (Enhanced Visualization)\nExternal Dependencies\nCore Components\ntears.py (Tear Sheet Generation)\nplotting.py (Visualization)\ntimeseries.py (Returns Analysis)\nutils.py (Helper Functions)\npos.py (Position Analysis)\ntxn.py (Transaction Analysis)\nperf_attrib.py (Performance Attribution)\nround_trips.py (Round Trip Analysis)\ncapacity.py (Strategy Capacity)\nempyrical (Performance Metrics)\npandas (Data Structures)\nnumpy (Numerical Operations)\nmatplotlib (Base Plotting)\nseaborn (Enhanced Visualization)\nThe architecture centers around the tear sheet generation system (tears.py), which coordinates the creation of various reports by calling specialized analysis modules. Each module focuses on a specific aspect of portfolio analysis:\ntears.py: Central orchestration for creating comprehensive tear sheets\nplotting.py: Visualization functions for creating plots\ntimeseries.py: Time series analysis of returns data\npos.py: Analysis of portfolio positions and exposures\ntxn.py: Transaction analysis and turnover calculations\nperf_attrib.py: Performance attribution to factors\nround_trips.py: Analysis of completed trades\ncapacity.py: Assessment of strategy capacity\nutils.py: Utility functions supporting other modules\nSources:pyfolio/__init__.py1-19setup.py44-54\nPyFolio processes financial data through a pipeline that transforms raw inputs into visual tear sheets. Understanding this data flow is essential to effectively using the library.\nVisualization (Tear Sheets)Processing PipelineInput DataReturns Time SeriesPosition RecordsTransaction RecordsBenchmark ReturnsRisk FactorsReturns Analysis(timeseries.py)Position Analysis(pos.py)Transaction Analysis(txn.py)Round Trip Analysis(round_trips.py)Performance Attribution(perf_attrib.py)Capacity Analysis(capacity.py)Returns Tear SheetPositions Tear SheetTransactions Tear SheetRound Trip Tear SheetPerformance Attribution Tear SheetCapacity Tear SheetFull Tear Sheet\nVisualization (Tear Sheets)\nProcessing Pipeline\nReturns Time Series\nPosition Records\nTransaction Records\nBenchmark Returns\nRisk Factors\nReturns Analysis(timeseries.py)\nPosition Analysis(pos.py)\nTransaction Analysis(txn.py)\nRound Trip Analysis(round_trips.py)\nPerformance Attribution(perf_attrib.py)\nCapacity Analysis(capacity.py)\nReturns Tear Sheet\nPositions Tear Sheet\nTransactions Tear Sheet\nRound Trip Tear Sheet\nPerformance Attribution Tear Sheet\nCapacity Tear Sheet\nFull Tear Sheet\nThe data flow begins with various input data types:\nReturns: Time series of portfolio returns (required)\nPositions: Records of portfolio holdings over time (optional)\nTransactions: Records of trades (optional)\nBenchmark Returns: Returns of a comparison benchmark (optional)\nRisk Factors: Factor returns for attribution analysis (optional)\nThese inputs are processed by specialized analysis modules, which calculate metrics and prepare data for visualization. The results are then rendered as tear sheets - comprehensive visual reports that help evaluate different aspects of portfolio performance.\nSources:README.md15-21\nTear Sheet Hierarchy\nTear sheets are the primary output of PyFolio. They provide visualizations and metrics to assess different aspects of portfolio performance. PyFolio offers several specialized tear sheets that can be used individually or combined into a comprehensive full tear sheet.\nKey Visualizationscreate_full_tear_sheet(Comprehensive Analysis)create_simple_tear_sheet(Basic Analysis)create_returns_tear_sheet(Returns Analysis)create_position_tear_sheet(Position Analysis)create_txn_tear_sheet(Transaction Analysis)create_round_trip_tear_sheet(Round Trip Analysis)create_interesting_times_tear_sheet(Performance During Key Events)create_capacity_tear_sheet(Strategy Capacity)create_perf_attrib_tear_sheet(Factor Attribution)plot_returnsplot_rolling_returnsplot_drawdown_periodsplot_monthly_returns_heatmapplot_holdingsplot_position_exposuresplot_turnover\nKey Visualizations\ncreate_full_tear_sheet(Comprehensive Analysis)\ncreate_simple_tear_sheet(Basic Analysis)\ncreate_returns_tear_sheet(Returns Analysis)\ncreate_position_tear_sheet(Position Analysis)\ncreate_txn_tear_sheet(Transaction Analysis)\ncreate_round_trip_tear_sheet(Round Trip Analysis)\ncreate_interesting_times_tear_sheet(Performance During Key Events)\ncreate_capacity_tear_sheet(Strategy Capacity)\ncreate_perf_attrib_tear_sheet(Factor Attribution)\nplot_returns\nplot_rolling_returns\nplot_drawdown_periods\nplot_monthly_returns_heatmap\nplot_holdings\nplot_position_exposures\nplot_turnover\nThe tear sheet hierarchy shows how different reports are related:\nFull Tear Sheet- A comprehensive analysis combining all specialized tear sheets\nSimple Tear Sheet- A streamlined version focusing on returns, positions, and transactions\nSpecialized Tear Sheets:Returns Tear Sheet- Analysis of returns, drawdowns, and distributionPosition Tear Sheet- Analysis of holdings and exposuresTransaction Tear Sheet- Analysis of trading activity and turnoverRound Trip Tear Sheet- Analysis of completed tradesInteresting Times Tear Sheet- Performance during specific market eventsCapacity Tear Sheet- Assessment of strategy capacityPerformance Attribution Tear Sheet- Decomposition of returns into factor components\nReturns Tear Sheet- Analysis of returns, drawdowns, and distribution\nPosition Tear Sheet- Analysis of holdings and exposures\nTransaction Tear Sheet- Analysis of trading activity and turnover\nRound Trip Tear Sheet- Analysis of completed trades\nInteresting Times Tear Sheet- Performance during specific market events\nCapacity Tear Sheet- Assessment of strategy capacity\nPerformance Attribution Tear Sheet- Decomposition of returns into factor components\nEach tear sheet incorporates various plotting functions that visualize specific aspects of portfolio performance.\nSources:WHATSNEW.md7-16WHATSNEW.md29-43\nIntegration with External Systems\nPyFolio is designed to work with other financial analysis systems, particularly Zipline, but can be used with any source of portfolio data.\n\"Other Data Sources\"\"PyFolio (Analysis)\"\"Zipline (Backtesting)\"User\"Other Data Sources\"\"PyFolio (Analysis)\"\"Zipline (Backtesting)\"UserProcess backtest resultsalt[Direct Analysis]Run trading algorithm backtestextract_rets_pos_txn_from_zipline()Get portfolio dataReturns, positions, transactionsInput portfolio dataGenerate tear sheetsDisplay performance visualizations\nPyFolio integrates with external systems in the following ways:\nZipline Integration:Directly consumes Zipline backtest resultsUses utility functions to extract returns, positions, and transactions\nZipline Integration:\nDirectly consumes Zipline backtest results\nUses utility functions to extract returns, positions, and transactions\nEmpyrical Integration:Leverages the Empyrical library for performance metrics calculationsShares consistent risk and return calculations with Zipline\nEmpyrical Integration:\nLeverages the Empyrical library for performance metrics calculations\nShares consistent risk and return calculations with Zipline\nCustom Data Sources:Accepts pandas DataFrames from any sourceCan work with CSV files, databases, APIs, or other data providers\nCustom Data Sources:\nAccepts pandas DataFrames from any source\nCan work with CSV files, databases, APIs, or other data providers\nThis integration flexibility allows PyFolio to fit into various financial analysis workflows and accommodate different data sources.\nSources:setup.py44-54README.md10-11\nKey Features and Capabilities\nPyFolio provides a comprehensive suite of portfolio analysis tools. The table below summarizes the key features available:\nPyFolio offers both Bayesian and frequentist approaches to performance analysis, allowing for robust statistical assessment of trading strategies. The library continues to evolve with new features being added in each release.\nSources:WHATSNEW.md29-43WHATSNEW.md158-183\nVersion and Development\nPyFolio is an open-source project maintained by Quantopian Inc. The library is continuously improved with new features and bug fixes. Key development milestones include:\nAddition of performance attribution tear sheets\nSupport for international equities and alternative data sets\nImproved turnover calculation\nEnhanced visualization capabilities\nIntegration with the Empyrical library for performance metrics\nFor a full history of changes, see theDevelopment Guidesection.\nSources:README.md65-81WHATSNEW.md5-23\nRefresh this wiki\nOn this page\nSystem Architecture\nTear Sheet Hierarchy\nIntegration with External Systems\nKey Features and Capabilities\nVersion and Development",
246
+ "model": "gpt-4o",
247
+ "source": "selenium",
248
+ "success": true
249
+ },
250
+ "deepwiki_options": {
251
+ "enabled": true,
252
+ "model": "gpt-4o"
253
+ },
254
+ "risk": {
255
+ "import_feasibility": 0.85,
256
+ "intrusiveness_risk": "low",
257
+ "complexity": "medium"
258
+ }
259
+ }
pyfolio/mcp_output/env_info.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "environment": {
3
+ "type": "conda",
4
+ "name": "pyfolio_152676_env",
5
+ "files": {},
6
+ "python": "3.10",
7
+ "exec_prefix": []
8
+ },
9
+ "original_tests": {
10
+ "passed": false,
11
+ "report_path": null
12
+ },
13
+ "timestamp": 1760152922.5673006,
14
+ "conda_available": true
15
+ }
pyfolio/mcp_output/mcp_logs/llm_statistics.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "total_calls": 41,
3
+ "failed_calls": 0,
4
+ "retry_count": 0,
5
+ "total_prompt_tokens": 40507,
6
+ "total_completion_tokens": 12265,
7
+ "total_tokens": 52772,
8
+ "average_prompt_tokens": 987.9756097560976,
9
+ "average_completion_tokens": 299.1463414634146,
10
+ "average_tokens": 1287.121951219512
11
+ }
pyfolio/mcp_output/mcp_logs/run_log.json ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "timestamp": 1760153154.1336172,
3
+ "node": "RunNode",
4
+ "test_result": {
5
+ "passed": false,
6
+ "report_path": null,
7
+ "stdout": "",
8
+ "stderr": "hh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/mcp_output/mcp_plugin/mcp_service.py\", line 8, in <module>\n from pyfolio.tears import (\n File \"/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/source/pyfolio/__init__.py\", line 1, in <module>\n from . import utils\n File \"/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/source/pyfolio/utils.py\", line 21, in <module>\n from matplotlib.pyplot import cm\n File \"/home/wshiah/.local/lib/python3.10/site-packages/matplotlib/__init__.py\", line 161, in <module>\n from . import _api, _version, cbook, _docstring, rcsetup\n File \"/home/wshiah/.local/lib/python3.10/site-packages/matplotlib/rcsetup.py\", line 28, in <module>\n from matplotlib.colors import Colormap, is_color_like\n File \"/home/wshiah/.local/lib/python3.10/site-packages/matplotlib/colors.py\", line 52, in <module>\n from PIL import Image\nModuleNotFoundError: No module named 'PIL'\n\n"
9
+ },
10
+ "run_result": {
11
+ "success": false,
12
+ "test_passed": false,
13
+ "exit_code": 1,
14
+ "stdout": "",
15
+ "stderr": "hh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/mcp_output/mcp_plugin/mcp_service.py\", line 8, in <module>\n from pyfolio.tears import (\n File \"/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/source/pyfolio/__init__.py\", line 1, in <module>\n from . import utils\n File \"/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/source/pyfolio/utils.py\", line 21, in <module>\n from matplotlib.pyplot import cm\n File \"/home/wshiah/.local/lib/python3.10/site-packages/matplotlib/__init__.py\", line 161, in <module>\n from . import _api, _version, cbook, _docstring, rcsetup\n File \"/home/wshiah/.local/lib/python3.10/site-packages/matplotlib/rcsetup.py\", line 28, in <module>\n from matplotlib.colors import Colormap, is_color_like\n File \"/home/wshiah/.local/lib/python3.10/site-packages/matplotlib/colors.py\", line 52, in <module>\n from PIL import Image\nModuleNotFoundError: No module named 'PIL'\n\n",
16
+ "timestamp": 1760153154.1335971,
17
+ "error_type": "ImportError",
18
+ "error": "Module import failed: ERROR conda.cli.main_run:execute(41): `conda run python mcp_output/start_mcp.py` failed. (See above for error)\nTraceback (most recent call last):\n File \"/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/mcp_output/start_mcp.py\", line 17, in <module>\n from mcp_service import create_app\n File \"/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/mcp_output/mcp_plugin/mcp_service.py\", line 8, in <module>\n from pyfolio.tears import (\n File \"/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/source/pyfolio/__init__.py\", line 1, in <module>\n from . import utils\n File \"/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/source/pyfolio/utils.py\", line 21, in <module>\n from matplotlib.pyplot import cm\n File \"/home/wshiah/.local/lib/python3.10/site-packages/matplotlib/__init__.py\", line 161, in <module>\n from . import _api, _version, cbook, _docstring, rcsetup\n File \"/home/wshiah/.local/lib/python3.10/site-packages/matplotlib/rcsetup.py\", line 28, in <module>\n from matplotlib.colors import Colormap, is_color_like\n File \"/home/wshiah/.local/lib/python3.10/site-packages/matplotlib/colors.py\", line 52, in <module>\n from PIL import Image\nModuleNotFoundError: No module named 'PIL'\n\n",
19
+ "details": {
20
+ "command": "/home/wshiah/code/miniconda3/bin/conda run -n pyfolio_152676_env --cwd /export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio python mcp_output/start_mcp.py",
21
+ "working_directory": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio",
22
+ "environment_type": "conda"
23
+ }
24
+ },
25
+ "environment": {
26
+ "type": "conda",
27
+ "name": "pyfolio_152676_env",
28
+ "files": {},
29
+ "python": "3.10",
30
+ "exec_prefix": []
31
+ },
32
+ "plugin_info": {
33
+ "files": {
34
+ "mcp_output/start_mcp.py": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/mcp_output/start_mcp.py",
35
+ "mcp_output/mcp_plugin/__init__.py": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/mcp_output/mcp_plugin/__init__.py",
36
+ "mcp_output/mcp_plugin/mcp_service.py": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/mcp_output/mcp_plugin/mcp_service.py",
37
+ "mcp_output/mcp_plugin/adapter.py": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/mcp_output/mcp_plugin/adapter.py",
38
+ "mcp_output/mcp_plugin/main.py": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/mcp_output/mcp_plugin/main.py",
39
+ "mcp_output/requirements.txt": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/mcp_output/requirements.txt",
40
+ "mcp_output/README_MCP.md": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/mcp_output/README_MCP.md",
41
+ "mcp_output/tests_mcp/test_mcp_basic.py": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/mcp_output/tests_mcp/test_mcp_basic.py"
42
+ },
43
+ "adapter_mode": "import",
44
+ "endpoints": [
45
+ "create_returns_tear_sheet",
46
+ "create_position_tear_sheet",
47
+ "create_txn_tear_sheet",
48
+ "show_worst_drawdown_periods",
49
+ "plot_rolling_returns",
50
+ "plot_rolling_beta",
51
+ "plot_rolling_volatility",
52
+ "plot_drawdown_periods",
53
+ "plot_monthly_returns_heatmap",
54
+ "plot_monthly_returns_dist",
55
+ "plot_holdings",
56
+ "plot_sector_allocations",
57
+ "cum_returns",
58
+ "cum_returns_final",
59
+ "aggregate_returns",
60
+ "annual_return",
61
+ "annual_volatility",
62
+ "sharpe_ratio",
63
+ "sortino_ratio",
64
+ "max_drawdown",
65
+ "alpha_beta",
66
+ "beta",
67
+ "alpha",
68
+ "stability_of_timeseries",
69
+ "tail_ratio",
70
+ "value_at_risk",
71
+ "capture",
72
+ "up_capture",
73
+ "down_capture",
74
+ "create_full_tear_sheet",
75
+ "create_simple_tear_sheet",
76
+ "create_interesting_periods_tear_sheet",
77
+ "compute_max_capacity",
78
+ "compute_capacity",
79
+ "extract_returns",
80
+ "extract_positions",
81
+ "extract_transactions",
82
+ "extract_benchmark_returns",
83
+ "extract_interesting_periods",
84
+ "extract_sector_allocations"
85
+ ],
86
+ "mcp_dir": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/mcp_output/mcp_plugin",
87
+ "tests_dir": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/mcp_output/tests_mcp",
88
+ "main_entry": "start_mcp.py",
89
+ "readme_path": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/pyfolio/mcp_output/README_MCP.md",
90
+ "requirements": [
91
+ "fastmcp>=0.1.0",
92
+ "pydantic>=2.0.0"
93
+ ]
94
+ },
95
+ "fastmcp_installed": false
96
+ }
pyfolio/mcp_output/mcp_plugin/__init__.py ADDED
File without changes
pyfolio/mcp_output/mcp_plugin/__pycache__/adapter.cpython-310.pyc ADDED
Binary file (11.1 kB). View file
 
pyfolio/mcp_output/mcp_plugin/__pycache__/mcp_service.cpython-310.pyc ADDED
Binary file (6.68 kB). View file
 
pyfolio/mcp_output/mcp_plugin/adapter.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ # Path settings
5
+ source_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "source")
6
+ sys.path.insert(0, source_path)
7
+
8
+ # Import statements
9
+ from pyfolio.tears import create_full_tear_sheet, create_simple_tear_sheet, create_returns_tear_sheet, create_position_tear_sheet, create_txn_tear_sheet, create_round_trip_tear_sheet, create_interesting_times_tear_sheet, create_capacity_tear_sheet, create_perf_attrib_tear_sheet
10
+ from pyfolio.plotting import plot_returns, plot_rolling_returns, plot_drawdown_periods, plot_monthly_returns_heatmap, plot_holdings, plot_position_exposures, plot_turnover
11
+ from pyfolio.timeseries import timeseries
12
+ from pyfolio.utils import utils
13
+ from pyfolio.capacity import capacity
14
+ from pyfolio.round_trips import round_trips
15
+ from pyfolio.perf_attrib import perf_attrib
16
+ from pyfolio.txn import txn
17
+ from pyfolio.pos import pos
18
+
19
+ # Adapter class
20
+ class Adapter:
21
+ """
22
+ Adapter class for the MCP plugin to integrate with the PyFolio library.
23
+ Provides methods to utilize all identified functions and classes from the PyFolio library.
24
+ """
25
+
26
+ def __init__(self):
27
+ """
28
+ Initialize the Adapter class with default mode set to 'import'.
29
+ """
30
+ self.mode = "import"
31
+
32
+ # -------------------------------------------------------------------------
33
+ # Tear Sheet Generation Methods
34
+ # -------------------------------------------------------------------------
35
+
36
+ def generate_full_tear_sheet(self, returns, positions=None, transactions=None, **kwargs):
37
+ """
38
+ Generate a comprehensive full tear sheet.
39
+
40
+ Parameters:
41
+ - returns: pandas.Series of portfolio returns.
42
+ - positions: pandas.DataFrame of portfolio positions (optional).
43
+ - transactions: pandas.DataFrame of portfolio transactions (optional).
44
+ - kwargs: Additional arguments for customization.
45
+
46
+ Returns:
47
+ - dict: Status and result of the operation.
48
+ """
49
+ try:
50
+ create_full_tear_sheet(returns, positions=positions, transactions=transactions, **kwargs)
51
+ return {"status": "success", "message": "Full tear sheet generated successfully."}
52
+ except Exception as e:
53
+ return {"status": "error", "message": f"Failed to generate full tear sheet: {str(e)}"}
54
+
55
+ def generate_simple_tear_sheet(self, returns, **kwargs):
56
+ """
57
+ Generate a simple tear sheet.
58
+
59
+ Parameters:
60
+ - returns: pandas.Series of portfolio returns.
61
+ - kwargs: Additional arguments for customization.
62
+
63
+ Returns:
64
+ - dict: Status and result of the operation.
65
+ """
66
+ try:
67
+ create_simple_tear_sheet(returns, **kwargs)
68
+ return {"status": "success", "message": "Simple tear sheet generated successfully."}
69
+ except Exception as e:
70
+ return {"status": "error", "message": f"Failed to generate simple tear sheet: {str(e)}"}
71
+
72
+ def generate_returns_tear_sheet(self, returns, **kwargs):
73
+ """
74
+ Generate a returns tear sheet.
75
+
76
+ Parameters:
77
+ - returns: pandas.Series of portfolio returns.
78
+ - kwargs: Additional arguments for customization.
79
+
80
+ Returns:
81
+ - dict: Status and result of the operation.
82
+ """
83
+ try:
84
+ create_returns_tear_sheet(returns, **kwargs)
85
+ return {"status": "success", "message": "Returns tear sheet generated successfully."}
86
+ except Exception as e:
87
+ return {"status": "error", "message": f"Failed to generate returns tear sheet: {str(e)}"}
88
+
89
+ def generate_position_tear_sheet(self, positions, **kwargs):
90
+ """
91
+ Generate a position tear sheet.
92
+
93
+ Parameters:
94
+ - positions: pandas.DataFrame of portfolio positions.
95
+ - kwargs: Additional arguments for customization.
96
+
97
+ Returns:
98
+ - dict: Status and result of the operation.
99
+ """
100
+ try:
101
+ create_position_tear_sheet(positions, **kwargs)
102
+ return {"status": "success", "message": "Position tear sheet generated successfully."}
103
+ except Exception as e:
104
+ return {"status": "error", "message": f"Failed to generate position tear sheet: {str(e)}"}
105
+
106
+ def generate_transaction_tear_sheet(self, transactions, **kwargs):
107
+ """
108
+ Generate a transaction tear sheet.
109
+
110
+ Parameters:
111
+ - transactions: pandas.DataFrame of portfolio transactions.
112
+ - kwargs: Additional arguments for customization.
113
+
114
+ Returns:
115
+ - dict: Status and result of the operation.
116
+ """
117
+ try:
118
+ create_txn_tear_sheet(transactions, **kwargs)
119
+ return {"status": "success", "message": "Transaction tear sheet generated successfully."}
120
+ except Exception as e:
121
+ return {"status": "error", "message": f"Failed to generate transaction tear sheet: {str(e)}"}
122
+
123
+ def generate_round_trip_tear_sheet(self, transactions, **kwargs):
124
+ """
125
+ Generate a round trip tear sheet.
126
+
127
+ Parameters:
128
+ - transactions: pandas.DataFrame of portfolio transactions.
129
+ - kwargs: Additional arguments for customization.
130
+
131
+ Returns:
132
+ - dict: Status and result of the operation.
133
+ """
134
+ try:
135
+ create_round_trip_tear_sheet(transactions, **kwargs)
136
+ return {"status": "success", "message": "Round trip tear sheet generated successfully."}
137
+ except Exception as e:
138
+ return {"status": "error", "message": f"Failed to generate round trip tear sheet: {str(e)}"}
139
+
140
+ def generate_interesting_times_tear_sheet(self, returns, **kwargs):
141
+ """
142
+ Generate an interesting times tear sheet.
143
+
144
+ Parameters:
145
+ - returns: pandas.Series of portfolio returns.
146
+ - kwargs: Additional arguments for customization.
147
+
148
+ Returns:
149
+ - dict: Status and result of the operation.
150
+ """
151
+ try:
152
+ create_interesting_times_tear_sheet(returns, **kwargs)
153
+ return {"status": "success", "message": "Interesting times tear sheet generated successfully."}
154
+ except Exception as e:
155
+ return {"status": "error", "message": f"Failed to generate interesting times tear sheet: {str(e)}"}
156
+
157
+ def generate_capacity_tear_sheet(self, returns, **kwargs):
158
+ """
159
+ Generate a capacity tear sheet.
160
+
161
+ Parameters:
162
+ - returns: pandas.Series of portfolio returns.
163
+ - kwargs: Additional arguments for customization.
164
+
165
+ Returns:
166
+ - dict: Status and result of the operation.
167
+ """
168
+ try:
169
+ create_capacity_tear_sheet(returns, **kwargs)
170
+ return {"status": "success", "message": "Capacity tear sheet generated successfully."}
171
+ except Exception as e:
172
+ return {"status": "error", "message": f"Failed to generate capacity tear sheet: {str(e)}"}
173
+
174
+ def generate_performance_attribution_tear_sheet(self, returns, factor_returns, **kwargs):
175
+ """
176
+ Generate a performance attribution tear sheet.
177
+
178
+ Parameters:
179
+ - returns: pandas.Series of portfolio returns.
180
+ - factor_returns: pandas.DataFrame of factor returns.
181
+ - kwargs: Additional arguments for customization.
182
+
183
+ Returns:
184
+ - dict: Status and result of the operation.
185
+ """
186
+ try:
187
+ create_perf_attrib_tear_sheet(returns, factor_returns, **kwargs)
188
+ return {"status": "success", "message": "Performance attribution tear sheet generated successfully."}
189
+ except Exception as e:
190
+ return {"status": "error", "message": f"Failed to generate performance attribution tear sheet: {str(e)}"}
191
+
192
+ # -------------------------------------------------------------------------
193
+ # Plotting Methods
194
+ # -------------------------------------------------------------------------
195
+
196
+ def plot_portfolio_returns(self, returns):
197
+ """
198
+ Plot portfolio returns.
199
+
200
+ Parameters:
201
+ - returns: pandas.Series of portfolio returns.
202
+
203
+ Returns:
204
+ - dict: Status and result of the operation.
205
+ """
206
+ try:
207
+ plot_returns(returns)
208
+ return {"status": "success", "message": "Portfolio returns plotted successfully."}
209
+ except Exception as e:
210
+ return {"status": "error", "message": f"Failed to plot portfolio returns: {str(e)}"}
211
+
212
+ def plot_rolling_returns(self, returns, benchmark_returns=None):
213
+ """
214
+ Plot rolling returns.
215
+
216
+ Parameters:
217
+ - returns: pandas.Series of portfolio returns.
218
+ - benchmark_returns: pandas.Series of benchmark returns (optional).
219
+
220
+ Returns:
221
+ - dict: Status and result of the operation.
222
+ """
223
+ try:
224
+ plot_rolling_returns(returns, benchmark_returns=benchmark_returns)
225
+ return {"status": "success", "message": "Rolling returns plotted successfully."}
226
+ except Exception as e:
227
+ return {"status": "error", "message": f"Failed to plot rolling returns: {str(e)}"}
228
+
229
+ def plot_drawdown_periods(self, returns):
230
+ """
231
+ Plot drawdown periods.
232
+
233
+ Parameters:
234
+ - returns: pandas.Series of portfolio returns.
235
+
236
+ Returns:
237
+ - dict: Status and result of the operation.
238
+ """
239
+ try:
240
+ plot_drawdown_periods(returns)
241
+ return {"status": "success", "message": "Drawdown periods plotted successfully."}
242
+ except Exception as e:
243
+ return {"status": "error", "message": f"Failed to plot drawdown periods: {str(e)}"}
244
+
245
+ def plot_monthly_returns_heatmap(self, returns):
246
+ """
247
+ Plot monthly returns heatmap.
248
+
249
+ Parameters:
250
+ - returns: pandas.Series of portfolio returns.
251
+
252
+ Returns:
253
+ - dict: Status and result of the operation.
254
+ """
255
+ try:
256
+ plot_monthly_returns_heatmap(returns)
257
+ return {"status": "success", "message": "Monthly returns heatmap plotted successfully."}
258
+ except Exception as e:
259
+ return {"status": "error", "message": f"Failed to plot monthly returns heatmap: {str(e)}"}
260
+
261
+ def plot_holdings(self, positions):
262
+ """
263
+ Plot portfolio holdings.
264
+
265
+ Parameters:
266
+ - positions: pandas.DataFrame of portfolio positions.
267
+
268
+ Returns:
269
+ - dict: Status and result of the operation.
270
+ """
271
+ try:
272
+ plot_holdings(positions)
273
+ return {"status": "success", "message": "Portfolio holdings plotted successfully."}
274
+ except Exception as e:
275
+ return {"status": "error", "message": f"Failed to plot portfolio holdings: {str(e)}"}
276
+
277
+ def plot_position_exposures(self, positions):
278
+ """
279
+ Plot position exposures.
280
+
281
+ Parameters:
282
+ - positions: pandas.DataFrame of portfolio positions.
283
+
284
+ Returns:
285
+ - dict: Status and result of the operation.
286
+ """
287
+ try:
288
+ plot_position_exposures(positions)
289
+ return {"status": "success", "message": "Position exposures plotted successfully."}
290
+ except Exception as e:
291
+ return {"status": "error", "message": f"Failed to plot position exposures: {str(e)}"}
292
+
293
+ def plot_turnover(self, transactions):
294
+ """
295
+ Plot portfolio turnover.
296
+
297
+ Parameters:
298
+ - transactions: pandas.DataFrame of portfolio transactions.
299
+
300
+ Returns:
301
+ - dict: Status and result of the operation.
302
+ """
303
+ try:
304
+ plot_turnover(transactions)
305
+ return {"status": "success", "message": "Portfolio turnover plotted successfully."}
306
+ except Exception as e:
307
+ return {"status": "error", "message": f"Failed to plot portfolio turnover: {str(e)}"}
308
+
309
+ # -------------------------------------------------------------------------
310
+ # Utility Methods
311
+ # -------------------------------------------------------------------------
312
+
313
+ # Add additional utility methods as needed based on the analysis results.
314
+
315
+ # -------------------------------------------------------------------------
316
+ # Error Handling and Fallback
317
+ # -------------------------------------------------------------------------
318
+
319
+ def handle_import_failure(self):
320
+ """
321
+ Handle cases where imports fail.
322
+
323
+ Returns:
324
+ - dict: Status and fallback message.
325
+ """
326
+ return {"status": "error", "message": "Failed to import required modules. Ensure the PyFolio library is correctly installed and accessible."}
pyfolio/mcp_output/mcp_plugin/main.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MCP Service Auto-Wrapper - Auto-generated
3
+ """
4
+ from mcp_service import create_app
5
+
6
+ def main():
7
+ """Main entry point"""
8
+ app = create_app()
9
+ return app
10
+
11
+ if __name__ == "__main__":
12
+ app = main()
13
+ app.run()
pyfolio/mcp_output/mcp_plugin/mcp_service.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ source_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "source")
5
+ sys.path.insert(0, source_path)
6
+
7
+ from fastmcp import FastMCP
8
+ from pyfolio.tears import (
9
+ create_full_tear_sheet,
10
+ create_simple_tear_sheet,
11
+ create_returns_tear_sheet,
12
+ create_position_tear_sheet,
13
+ create_txn_tear_sheet,
14
+ create_round_trip_tear_sheet,
15
+ create_interesting_times_tear_sheet,
16
+ create_capacity_tear_sheet,
17
+ create_perf_attrib_tear_sheet,
18
+ )
19
+ from pyfolio.plotting import (
20
+ axes_style,
21
+ customize,
22
+ plot_annual_returns,
23
+ plot_capacity_sweep,
24
+ plot_cones,
25
+ plot_daily_turnover_hist,
26
+ plot_daily_volume,
27
+ plot_drawdown_periods,
28
+ plot_drawdown_underwater,
29
+ plot_exposures,
30
+ plot_gross_leverage,
31
+ plot_holdings,
32
+ plot_long_short_holdings,
33
+ plot_max_median_position_concentration,
34
+ plot_monthly_returns_dist,
35
+ plot_monthly_returns_heatmap,
36
+ plot_monthly_returns_timeseries,
37
+ plot_perf_stats,
38
+ plot_prob_profit_trade,
39
+ plot_return_quantiles,
40
+ plot_returns,
41
+ plot_rolling_beta,
42
+ plot_rolling_returns,
43
+ plot_rolling_sharpe,
44
+ plot_rolling_volatility,
45
+ plot_round_trip_lifetimes,
46
+ plot_sector_allocations,
47
+ plot_slippage_sensitivity,
48
+ plot_slippage_sweep,
49
+ plot_turnover,
50
+ plot_txn_time_hist,
51
+ plotting_context,
52
+ show_and_plot_top_positions,
53
+ show_perf_stats,
54
+ show_profit_attribution,
55
+ show_worst_drawdown_periods,
56
+ )
57
+
58
+ mcp = FastMCP("pyfolio_service")
59
+
60
+ @mcp.tool(name="generate_full_tear_sheet", description="Generate a comprehensive tear sheet for portfolio analysis.")
61
+ def generate_full_tear_sheet(returns: list, positions: dict = None, transactions: dict = None, benchmark_rets: list = None) -> dict:
62
+ try:
63
+ create_full_tear_sheet(returns, positions, transactions, benchmark_rets)
64
+ return {"success": True, "result": "Full tear sheet generated successfully.", "error": None}
65
+ except Exception as e:
66
+ return {"success": False, "result": None, "error": str(e)}
67
+
68
+ @mcp.tool(name="generate_simple_tear_sheet", description="Generate a basic tear sheet for portfolio analysis.")
69
+ def generate_simple_tear_sheet(returns: list) -> dict:
70
+ try:
71
+ create_simple_tear_sheet(returns)
72
+ return {"success": True, "result": "Simple tear sheet generated successfully.", "error": None}
73
+ except Exception as e:
74
+ return {"success": False, "result": None, "error": str(e)}
75
+
76
+ @mcp.tool(name="generate_returns_tear_sheet", description="Generate a tear sheet for returns analysis.")
77
+ def generate_returns_tear_sheet(returns: list) -> dict:
78
+ try:
79
+ create_returns_tear_sheet(returns)
80
+ return {"success": True, "result": "Returns tear sheet generated successfully.", "error": None}
81
+ except Exception as e:
82
+ return {"success": False, "result": None, "error": str(e)}
83
+
84
+ @mcp.tool(name="generate_position_tear_sheet", description="Generate a tear sheet for position analysis.")
85
+ def generate_position_tear_sheet(positions: dict) -> dict:
86
+ try:
87
+ create_position_tear_sheet(positions)
88
+ return {"success": True, "result": "Position tear sheet generated successfully.", "error": None}
89
+ except Exception as e:
90
+ return {"success": False, "result": None, "error": str(e)}
91
+
92
+ @mcp.tool(name="generate_transaction_tear_sheet", description="Generate a tear sheet for transaction analysis.")
93
+ def generate_transaction_tear_sheet(transactions: dict) -> dict:
94
+ try:
95
+ create_txn_tear_sheet(transactions)
96
+ return {"success": True, "result": "Transaction tear sheet generated successfully.", "error": None}
97
+ except Exception as e:
98
+ return {"success": False, "result": None, "error": str(e)}
99
+
100
+ @mcp.tool(name="generate_round_trip_tear_sheet", description="Generate a tear sheet for round trip analysis.")
101
+ def generate_round_trip_tear_sheet(round_trips: dict) -> dict:
102
+ try:
103
+ create_round_trip_tear_sheet(round_trips)
104
+ return {"success": True, "result": "Round trip tear sheet generated successfully.", "error": None}
105
+ except Exception as e:
106
+ return {"success": False, "result": None, "error": str(e)}
107
+
108
+ @mcp.tool(name="generate_interesting_times_tear_sheet", description="Generate a tear sheet for performance during key events.")
109
+ def generate_interesting_times_tear_sheet(returns: list, events: list) -> dict:
110
+ try:
111
+ create_interesting_times_tear_sheet(returns, events)
112
+ return {"success": True, "result": "Interesting times tear sheet generated successfully.", "error": None}
113
+ except Exception as e:
114
+ return {"success": False, "result": None, "error": str(e)}
115
+
116
+ @mcp.tool(name="generate_capacity_tear_sheet", description="Generate a tear sheet for strategy capacity analysis.")
117
+ def generate_capacity_tear_sheet(returns: list, positions: dict) -> dict:
118
+ try:
119
+ create_capacity_tear_sheet(returns, positions)
120
+ return {"success": True, "result": "Capacity tear sheet generated successfully.", "error": None}
121
+ except Exception as e:
122
+ return {"success": False, "result": None, "error": str(e)}
123
+
124
+ @mcp.tool(name="generate_performance_attribution_tear_sheet", description="Generate a tear sheet for performance attribution analysis.")
125
+ def generate_performance_attribution_tear_sheet(returns: list, factors: dict) -> dict:
126
+ try:
127
+ create_perf_attrib_tear_sheet(returns, factors)
128
+ return {"success": True, "result": "Performance attribution tear sheet generated successfully.", "error": None}
129
+ except Exception as e:
130
+ return {"success": False, "result": None, "error": str(e)}
131
+
132
+ @mcp.tool(name="plot_annual_returns", description="Plot annual returns as a bar chart.")
133
+ def plot_annual_returns_tool(returns: list) -> dict:
134
+ try:
135
+ ax = plot_annual_returns(returns)
136
+ return {"success": True, "result": ax, "error": None}
137
+ except Exception as e:
138
+ return {"success": False, "result": None, "error": str(e)}
139
+
140
+ @mcp.tool(name="plot_monthly_returns_heatmap", description="Plot a heatmap of monthly returns.")
141
+ def plot_monthly_returns_heatmap_tool(returns: list) -> dict:
142
+ try:
143
+ ax = plot_monthly_returns_heatmap(returns)
144
+ return {"success": True, "result": ax, "error": None}
145
+ except Exception as e:
146
+ return {"success": False, "result": None, "error": str(e)}
147
+
148
+ @mcp.tool(name="plot_drawdown_periods", description="Plot cumulative returns highlighting top drawdown periods.")
149
+ def plot_drawdown_periods_tool(returns: list, top: int = 10) -> dict:
150
+ try:
151
+ ax = plot_drawdown_periods(returns, top)
152
+ return {"success": True, "result": ax, "error": None}
153
+ except Exception as e:
154
+ return {"success": False, "result": None, "error": str(e)}
155
+
156
+ @mcp.tool(name="plot_rolling_returns", description="Plot cumulative rolling returns versus benchmarks.")
157
+ def plot_rolling_returns_tool(returns: list, factor_returns: list = None, live_start_date: str = None) -> dict:
158
+ try:
159
+ ax = plot_rolling_returns(returns, factor_returns, live_start_date)
160
+ return {"success": True, "result": ax, "error": None}
161
+ except Exception as e:
162
+ return {"success": False, "result": None, "error": str(e)}
163
+
164
+ @mcp.tool(name="plot_turnover", description="Plot turnover over time.")
165
+ def plot_turnover_tool(returns: list, transactions: dict, positions: dict, turnover_denom: str = "AGB") -> dict:
166
+ try:
167
+ ax = plot_turnover(returns, transactions, positions, turnover_denom)
168
+ return {"success": True, "result": ax, "error": None}
169
+ except Exception as e:
170
+ return {"success": False, "result": None, "error": str(e)}
171
+
172
+ def create_app() -> FastMCP:
173
+ """
174
+ Create and return the FastMCP application instance.
175
+
176
+ Returns:
177
+ FastMCP: The FastMCP application instance.
178
+ """
179
+ return mcp
pyfolio/mcp_output/requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastmcp>=0.1.0
2
+ pydantic>=2.0.0
3
+ numpy
4
+ pandas
5
+ matplotlib
6
+ seaborn
7
+ scipy
8
+ statsmodels
9
+
10
+ # Optional Dependencies
11
+ # jupyter
12
+ # pytest
pyfolio/mcp_output/simple_revise_error_analysis.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "status": "FAIL",
3
+ "next_action": "fix_directly",
4
+ "confidence": 0.9,
5
+ "summary": {
6
+ "error_type": "ModuleNotFoundError",
7
+ "error_message": "No module named 'PIL'",
8
+ "analysis": [
9
+ {
10
+ "description": "The error occurs because the Python Imaging Library (Pillow) is not installed in the environment. The 'PIL' module is part of Pillow, which is required by matplotlib.colors.",
11
+ "can_be_fixed_directly": true,
12
+ "repair_strategy": "Install the missing dependency 'Pillow' using the appropriate package manager (e.g., pip or conda)."
13
+ },
14
+ {
15
+ "historical_errors": [
16
+ {
17
+ "node": "CodeCheckNode",
18
+ "type": "ImportError",
19
+ "message": "Function 'plot_position_exposures' does not exist in module 'pyfolio.plotting'"
20
+ },
21
+ {
22
+ "node": "RunNode",
23
+ "type": "PluginSmokeFailed",
24
+ "message": "Module import failed: ERROR conda.cli.main_run:execute(41): `conda run python mcp_output/start_mcp.py` failed."
25
+ },
26
+ {
27
+ "node": "RunNode",
28
+ "type": "RuntimeError",
29
+ "message": "Module import failed: ERROR conda.cli.main_run:execute(41): `conda run python mcp_output/start_mcp.py` failed."
30
+ }
31
+ ],
32
+ "note": "The current error is unrelated to the historical errors but may indicate broader dependency management issues in the project."
33
+ }
34
+ ]
35
+ }
36
+ }
pyfolio/mcp_output/start_mcp.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MCP Service Startup Entry
3
+ """
4
+ import sys
5
+ import os
6
+
7
+ project_root = os.path.dirname(os.path.abspath(__file__))
8
+ mcp_plugin_dir = os.path.join(project_root, "mcp_plugin")
9
+ if mcp_plugin_dir not in sys.path:
10
+ sys.path.insert(0, mcp_plugin_dir)
11
+
12
+ # Set path to source directory
13
+ source_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "source")
14
+ sys.path.insert(0, source_path)
15
+
16
+ # Ensure required dependencies are available
17
+ try:
18
+ from PIL import Image # Verify Pillow is installed
19
+ except ImportError:
20
+ raise ImportError("Pillow is not installed. Please install it using 'pip install pillow'.")
21
+
22
+ from mcp_service import create_app
23
+
24
+ def main():
25
+ """Start FastMCP service"""
26
+ app = create_app()
27
+ # Use environment variable to configure port, default 8000
28
+ port = int(os.environ.get("MCP_PORT", "8000"))
29
+
30
+ # Choose transport mode based on environment variable
31
+ transport = os.environ.get("MCP_TRANSPORT", "stdio")
32
+ if transport == "http":
33
+ app.run(transport="http", host="0.0.0.0", port=port)
34
+ else:
35
+ # Default to STDIO mode
36
+ app.run()
37
+
38
+ if __name__ == "__main__":
39
+ main()
pyfolio/mcp_output/tests_mcp/test_mcp_basic.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MCP Service Basic Test
3
+ """
4
+ import sys
5
+ import os
6
+
7
+ project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
8
+ mcp_plugin_dir = os.path.join(project_root, "mcp_plugin")
9
+ if mcp_plugin_dir not in sys.path:
10
+ sys.path.insert(0, mcp_plugin_dir)
11
+
12
+ source_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "source")
13
+ sys.path.insert(0, source_path)
14
+
15
+ def test_import_mcp_service():
16
+ """Test if MCP service can be imported normally"""
17
+ try:
18
+ from mcp_service import create_app
19
+ app = create_app()
20
+ assert app is not None
21
+ print("MCP service imported successfully")
22
+ return True
23
+ except Exception as e:
24
+ print("MCP service import failed: " + str(e))
25
+ return False
26
+
27
+ def test_adapter_init():
28
+ """Test if adapter can be initialized normally"""
29
+ try:
30
+ from adapter import Adapter
31
+ adapter = Adapter()
32
+ assert adapter is not None
33
+ print("Adapter initialized successfully")
34
+ return True
35
+ except Exception as e:
36
+ print("Adapter initialization failed: " + str(e))
37
+ return False
38
+
39
+ if __name__ == "__main__":
40
+ print("Running MCP service basic test...")
41
+ test1 = test_import_mcp_service()
42
+ test2 = test_adapter_init()
43
+
44
+ if test1 and test2:
45
+ print("All basic tests passed")
46
+ sys.exit(0)
47
+ else:
48
+ print("Some tests failed")
49
+ sys.exit(1)
pyfolio/mcp_output/tests_smoke/test_smoke.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib, sys
2
+ import os
3
+
4
+ # Add current directory to Python path
5
+ sys.path.insert(0, os.getcwd())
6
+
7
+ source_dir = os.path.join(os.getcwd(), "source")
8
+ if os.path.exists(source_dir):
9
+ sys.path.insert(0, source_dir)
10
+
11
+
12
+ try:
13
+ importlib.import_module("pyfolio")
14
+ print("OK - Successfully imported pyfolio")
15
+ except ImportError as e:
16
+ print(f"Failed to import pyfolio: {e}")
17
+ fallback_packages = []
18
+
19
+ fallback_packages = ['pyfolio']
20
+
21
+ for pkg in fallback_packages:
22
+ try:
23
+ importlib.import_module(pkg)
24
+ print(f"OK - Successfully imported {pkg}")
25
+ break
26
+ except ImportError:
27
+ continue
28
+ else:
29
+ print("All import attempts failed")
pyfolio/source/.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ pyfolio/_version.py export-subst
pyfolio/source/.github/ISSUE_TEMPLATE.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Problem Description
2
+
3
+ **Please provide a minimal, self-contained, and reproducible example:**
4
+ ```python
5
+ [Paste code here]
6
+ ```
7
+
8
+ **Please provide the full traceback:**
9
+ ```python
10
+ [Paste traceback here]
11
+ ```
12
+
13
+ **Please provide any additional information below:**
14
+
15
+
16
+ ## Versions
17
+
18
+ * Pyfolio version:
19
+ * Python version:
20
+ * Pandas version:
21
+ * Matplotlib version:
pyfolio/source/.gitignore ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+
5
+ # C extensions
6
+ *.so
7
+
8
+ # Distribution / packaging
9
+ .Python
10
+ env/
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ *.egg-info/
23
+ .installed.cfg
24
+ *.egg
25
+
26
+ # PyInstaller
27
+ # Usually these files are written by a python script from a template
28
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
29
+ *.manifest
30
+ *.spec
31
+
32
+ # Installer logs
33
+ pip-log.txt
34
+ pip-delete-this-directory.txt
35
+
36
+ # Unit test / coverage reports
37
+ htmlcov/
38
+ .tox/
39
+ .coverage
40
+ .coverage.*
41
+ .cache
42
+ nosetests.xml
43
+ coverage.xml
44
+ *,cover
45
+
46
+ # Translations
47
+ *.mo
48
+ *.pot
49
+
50
+ # Django stuff:
51
+ *.log
52
+
53
+ # Sphinx documentation
54
+ docs/_build/
55
+
56
+ # PyBuilder
57
+ target/
58
+
59
+ # VIM
60
+ *.sw?
61
+
62
+ # IPython notebook checkpoints
63
+ .ipynb_checkpoints/
pyfolio/source/.travis.yml ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ language: python
2
+ sudo: false
3
+
4
+ python:
5
+ - 2.7
6
+ - 3.7
7
+
8
+ env:
9
+ - PANDAS_VERSION=0.18.1
10
+ - PANDAS_VERSION=0.25.0
11
+
12
+ matrix:
13
+ exclude:
14
+ - python: 3.7
15
+ env: PANDAS_VERSION=0.18.1
16
+ - python: 2.7
17
+ env: PANDAS_VERSION=0.25.0
18
+
19
+ before_install:
20
+ # We do this conditionally because it saves us some downloading if the
21
+ # version is the same.
22
+ - if [[ "$TRAVIS_PYTHON_VERSION" == "2.7" ]]; then
23
+ wget https://repo.continuum.io/miniconda/Miniconda-latest-Linux-x86_64.sh -O miniconda.sh;
24
+ else
25
+ wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh;
26
+ fi
27
+ - bash miniconda.sh -b -p $HOME/miniconda
28
+ - export PATH="$HOME/miniconda/bin:$PATH"
29
+ # required for using mkl-service
30
+ - export MKL_THREADING_LAYER=GNU
31
+ - hash -r
32
+ - conda config --set always_yes yes --set changeps1 no
33
+ - conda update -q conda
34
+ # Useful for debugging any issues with conda
35
+ - conda info -a
36
+ - cp pyfolio/tests/matplotlibrc .
37
+
38
+ install:
39
+ - conda create -q -n testenv --yes python=$TRAVIS_PYTHON_VERSION ipython numpy scipy nose matplotlib pandas=$PANDAS_VERSION flake8 seaborn scikit-learn runipy pandas-datareader
40
+ - source activate testenv
41
+ - pip install -e .[all]
42
+
43
+ before_script:
44
+ - "flake8 pyfolio"
45
+
46
+ script:
47
+ - nosetests $TESTCMD
48
+
49
+ notifications:
50
+ email: false
51
+
52
+ branches:
53
+ only:
54
+ - master
pyfolio/source/LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 2018 Quantopian, Inc.
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
+
pyfolio/source/MANIFEST.in ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ include versioneer.py
2
+ include pyfolio/_version.py
3
+ include LICENSE
pyfolio/source/README.md ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ![pyfolio](https://media.quantopian.com/logos/open_source/pyfolio-logo-03.png "pyfolio")
2
+
3
+ # pyfolio
4
+
5
+ [![Join the chat at https://gitter.im/quantopian/pyfolio](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/quantopian/pyfolio?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
6
+ [![build status](https://travis-ci.org/quantopian/pyfolio.png?branch=master)](https://travis-ci.org/quantopian/pyfolio)
7
+
8
+ pyfolio is a Python library for performance and risk analysis of
9
+ financial portfolios developed by
10
+ [Quantopian Inc](https://www.quantopian.com). It works well with the
11
+ [Zipline](https://www.zipline.io/) open source backtesting library.
12
+ Quantopian also offers a [fully managed service for professionals](https://factset.quantopian.com)
13
+ that includes Zipline, Alphalens, Pyfolio, FactSet data, and more.
14
+
15
+ At the core of pyfolio is a so-called tear sheet that consists of
16
+ various individual plots that provide a comprehensive image of the
17
+ performance of a trading algorithm. Here's an example of a simple tear
18
+ sheet analyzing a strategy:
19
+
20
+ ![simple tear 0](https://github.com/quantopian/pyfolio/raw/master/docs/simple_tear_0.png "Example tear sheet created from a Zipline algo")
21
+ ![simple tear 1](https://github.com/quantopian/pyfolio/raw/master/docs/simple_tear_1.png "Example tear sheet created from a Zipline algo")
22
+
23
+ Also see [slides of a talk about
24
+ pyfolio](https://nbviewer.jupyter.org/format/slides/github/quantopian/pyfolio/blob/master/pyfolio/examples/pyfolio_talk_slides.ipynb#/).
25
+
26
+ ## Installation
27
+
28
+ To install pyfolio, run:
29
+
30
+ ```bash
31
+ pip install pyfolio
32
+ ```
33
+
34
+ #### Development
35
+
36
+ For development, you may want to use a [virtual environment](https://docs.python-guide.org/en/latest/dev/virtualenvs/) to avoid dependency conflicts between pyfolio and other Python projects you have. To get set up with a virtual env, run:
37
+ ```bash
38
+ mkvirtualenv pyfolio
39
+ ```
40
+
41
+ Next, clone this git repository and run `python setup.py develop`
42
+ and edit the library files directly.
43
+
44
+ #### Matplotlib on OSX
45
+
46
+ If you are on OSX and using a non-framework build of Python, you may need to set your backend:
47
+ ``` bash
48
+ echo "backend: TkAgg" > ~/.matplotlib/matplotlibrc
49
+ ```
50
+
51
+ ## Usage
52
+
53
+ A good way to get started is to run the pyfolio examples in
54
+ a [Jupyter notebook](https://jupyter.org/). To do this, you first want to
55
+ start a Jupyter notebook server:
56
+
57
+ ```bash
58
+ jupyter notebook
59
+ ```
60
+
61
+ From the notebook list page, navigate to the pyfolio examples directory
62
+ and open a notebook. Execute the code in a notebook cell by clicking on it
63
+ and hitting Shift+Enter.
64
+
65
+
66
+ ## Questions?
67
+
68
+ If you find a bug, feel free to [open an issue](https://github.com/quantopian/pyfolio/issues) in this repository.
69
+
70
+ You can also join our [mailing list](https://groups.google.com/forum/#!forum/pyfolio) or
71
+ our [Gitter channel](https://gitter.im/quantopian/pyfolio).
72
+
73
+ ## Support
74
+
75
+ Please [open an issue](https://github.com/quantopian/pyfolio/issues/new) for support.
76
+
77
+ ## Contributing
78
+
79
+ If you'd like to contribute, a great place to look is the [issues marked with help-wanted](https://github.com/quantopian/pyfolio/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22).
80
+
81
+ For a list of core developers and outside collaborators, see [the GitHub contributors list](https://github.com/quantopian/pyfolio/graphs/contributors).
pyfolio/source/WHATSNEW.md ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # What's New
2
+
3
+ These are new features and improvements of note in each release.
4
+
5
+ ## v0.9.0 (Aug 1st, 2018)
6
+
7
+ ### New features
8
+
9
+ - Previously, `pyfolio` has required a benchmark, usually the U.S. market
10
+ returns `SPY`. In order to provide support for international equities and
11
+ alternative data sets, `pyfolio` is now completely independent of benchmarks.
12
+ If a benchmark is passed, all benchmark-related analyses will be performed;
13
+ if not, they will simply be skipped. By [George Ho](https://github.com/eigenfoo)
14
+ - Performance attribution tearsheet [PR441](https://github.com/quantopian/pyfolio/pull/441), [PR433](https://github.com/quantopian/pyfolio/pull/433), [PR442](https://github.com/quantopian/pyfolio/pull/442). By [Vikram Narayan](https://github.com/vikram-narayan).
15
+ - Improved implementation of `get_turnover` [PR332](https://github.com/quantopian/pyfolio/pull/432). By [Gus Gordon](https://github.com/gusgordon).
16
+ - Users can now pass in extra rows (as a dict or OrderedDict) to display in the perf_stats table [PR445](https://github.com/quantopian/pyfolio/pull/445). By [Gus Gordon](https://github.com/gusgordon).
17
+
18
+ ### Maintenance
19
+
20
+ - Many features have been more extensively troubleshooted, maintained and
21
+ tested. By [Ana Ruelas](https://github.com/ahgnaw) and [Vikram
22
+ Narayan](https://github.com/vikram-narayan).
23
+ - Various fixes to support pandas versions >= 0.18.1 [PR443](https://github.com/quantopian/pyfolio/pull/443). By [Andrew Daniels](https://github.com/yankees714).
24
+
25
+ ## v0.8.0 (Aug 23rd, 2017)
26
+
27
+ This is a major release from `0.7.0`, and all users are recommended to upgrade.
28
+
29
+ ### New features
30
+
31
+ - Risk tear sheet: added a new tear sheet to analyze risk exposures to common
32
+ factors (e.g. mean reversion and momentum), sector (e.g. Morningstar
33
+ sectors), market cap and illiquid stocks. By [George
34
+ Ho](https://github.com/eigenfoo).
35
+ - Simple tear sheet: added a new tear sheet that presents only the most
36
+ important plots in the full tear sheet, for a quick general overview of a
37
+ portfolio's performance. By [George Ho](https://github.com/eigenfoo).
38
+ - Performance attribution: added new table to do performance attribution
39
+ analysis, such as the amount of returns attributable to common factors, and
40
+ summary statistics such as the multi-factor alpha and multi-factor Sharpe
41
+ ratio. By [Vikram Narayan](https://github.com/vikram-narayan).
42
+ - Volatility plot: added a rolling annual volatility plot to the returns tear
43
+ sheet. By [hkopp](https://github.com/hkopp).
44
+
45
+ ### Bugfixes
46
+
47
+ - Yahoo and pandas data-reader: fixed bug regarding Yahoo backend for market
48
+ data and pandas data-reader. By [Thomas Wiecki](https://github.com/twiecki)
49
+ and [Gus Gordon](https://github.com/gusgordon).
50
+ - `empyrical` compatibility: removed `information_ratio` to remain compatible
51
+ with `empyrical`. By [Thomas Wiecki](https://github.com/twiecki).
52
+ - Fama-French rolling multivariate regression: fixed bug where the rolling
53
+ Fama-French plot performed separate linear regressions instead of a
54
+ multivariate regression. By [George Ho](https://github.com/eigenfoo).
55
+ - Other minor bugfixes. By [Scott Sanderson](https://github.com/ssanderson),
56
+ [Jonathan Ng](https://github.com/jonathanng),
57
+ [SylvainDe](https://github.com/SylvainDe) and
58
+ [mckelvin](https://github.com/mckelvin).
59
+
60
+ ### Maintenance
61
+
62
+ - Documentation: updated and improved `pyfolio` documentation and example
63
+ Jupyter notebooks. By [George Ho](https://github.com/eigenfoo).
64
+ - Data loader migration: all data loaders have been migrated from `pyfolio` to
65
+ `empyrical`. By [James Christopher](https://github.com/jameschristopher).
66
+ - Improved plotting style: fixed issues with formatting and presentation of
67
+ plots. By [George Ho](https://github.com/eigenfoo).
68
+
69
+ ## v0.7.0 (Jan 28th, 2017)
70
+
71
+ This is a major release from `0.6.0`, and all users are recommended to upgrade.
72
+
73
+ ### New features
74
+
75
+ - Adds a transaction timing plot, which gives insight into the strategies'
76
+ trade times.
77
+ - Adds a plot showing the number of longs and shorts held over time.
78
+ - New round trips plot selects a sample of held positions (16 by default) and
79
+ shows their round trips. This replaces the old round trip plot, which became
80
+ unreadable for strategies that traded many positions.
81
+ - Adds basic capability for analyzing intraday strategies. If a strategy makes
82
+ a large amount of transactions relative to its end-of-day positions, then
83
+ pyfolio will attempt to reconstruct the intraday positions, take the point of
84
+ peak exposure to the market during each day, and plot that data with the
85
+ positions tear sheet. By default pyfolio will automatically detect this, but
86
+ the behavior can be changed by passing either `estimate_intraday=True` or
87
+ `estimate_intraday=False` to the tear sheet functions ([see
88
+ here](https://github.com/quantopian/pyfolio/blob/master/pyfolio/tears.py#L131)).
89
+ - Now formats [zipline](https://github.com/quantopian/zipline) assets,
90
+ displaying their ticker symbol.
91
+ - Gross leverage is no longer required to be passed, and will now be calculated
92
+ from the passed positions DataFrame.
93
+
94
+ ### Bugfixes
95
+
96
+ - Cone plotting location is now correct.
97
+ - Adjust scaling of beta and Fama-French plots.
98
+ - Removed multiple dependencies, some of which were previously unused.
99
+ - Various text fixes.
100
+
101
+ ## v0.6.0 (Oct 17, 2016)
102
+
103
+ This is a major new release from `0.5.1`. All users are recommended to upgrade.
104
+
105
+ ### New features
106
+
107
+ * Computation of performance and risk measures has been split off into
108
+ [`empyrical`](https://github.com/quantopian/empyrical). This allows
109
+ [`Zipline`](https://zipline.io) and `pyfolio` to use the same code to
110
+ calculate its risk statistics. By [Ana Ruelas](https://github.com/ahgnaw) and
111
+ [Abhi Kalyan](https://github.com/abhijeetkalyan).
112
+ * New multistrike cone which redraws the cone when it crossed its initial bounds
113
+ [PR310](https://github.com/quantopian/pyfolio/pull/310). By [Ana
114
+ Ruelas](https://github.com/ahgnaw) and [Abhi
115
+ Kalyan](https://github.com/abhijeetkalyan).
116
+
117
+ ### Bugfixes
118
+
119
+ * Can use most recent PyMC3 now.
120
+ * Depends on seaborn 0.7.0 or later now
121
+ [PR331](https://github.com/quantopian/pyfolio/pull/331).
122
+ * Disable buggy computation of round trips per day and per month
123
+ [PR339](https://github.com/quantopian/pyfolio/pull/339).
124
+
125
+ ## v0.5.1 (June 10, 2016)
126
+
127
+ This is a bugfix release from `0.5.0` with limited new functionality. All users are recommended to upgrade.
128
+
129
+ ### New features
130
+
131
+ * OOS data is now overlaid on top of box plot
132
+ [PR306](https://github.com/quantopian/pyfolio/pull/306) by [Ana
133
+ Ruelas](https://github.com/ahgnaw)
134
+ * New logo [PR298](https://github.com/quantopian/pyfolio/pull/298) by [Taso
135
+ Petridis](https://github.com/tasopetridis) and [Richard
136
+ Frank](https://github.com/richafrank)
137
+ * Raw returns plot and cumulative log returns plot
138
+ [PR294](https://github.com/quantopian/pyfolio/pull/294) by [Thomas
139
+ Wiecki](https://github.com/twiecki)
140
+ * Net exposure line to the long/short exposure plot
141
+ [PR301](https://github.com/quantopian/pyfolio/pull/301) by [Ana
142
+ Ruelas](https://github.com/ahgnaw)
143
+
144
+ ### Bugfixes
145
+
146
+ * Fix drawdown behavior and pandas exception in tear-sheet creation
147
+ [PR297](https://github.com/quantopian/pyfolio/pull/297) by [Flavio
148
+ Duarte](https://github.com/flaviodrt)
149
+
150
+ ## v0.5.0 (April 21, 2016) -- Olympia
151
+
152
+ This is a major release from `0.4.0` that includes many new analyses and
153
+ features. We recommend that all users upgrade to this new version. Also update
154
+ your dependencies, specifically, `pandas>=0.18.0`, `seaborn>=0.6.0` and
155
+ `zipline>=0.8.4`.
156
+
157
+ ### New features
158
+
159
+ * New capacity tear-sheet to assess how much capital can be traded on a strategy
160
+ [PR284](https://github.com/quantopian/pyfolio/pull/284). [Andrew
161
+ Campbell](https://github.com/a-campbell).
162
+ * Bootstrap analysis to assess uncertainty in performance metrics
163
+ [PR261](https://github.com/quantopian/pyfolio/pull/261). [Thomas
164
+ Wiecki](https://github.com/twiecki)
165
+ * Refactored round-trip analysis to be more general and have better output. Now
166
+ does full portfolio reconstruction to match trades
167
+ [PR293](https://github.com/quantopian/pyfolio/pull/293). [Thomas
168
+ Wiecki](https://github.com/twiecki), [Andrew
169
+ Campbell](https://github.com/a-campbell). See the
170
+ [tutorial](http://quantopian.github.io/pyfolio/round_trip_example/) for more
171
+ information.
172
+ * Prettier printing of tables in notebooks
173
+ [PR289](https://github.com/quantopian/pyfolio/pull/289). [Thomas
174
+ Wiecki](https://github.com/twiecki)
175
+ * Faster max-drawdown calculation
176
+ [PR281](https://github.com/quantopian/pyfolio/pull/281). [Devin
177
+ Stevenson](https://github.com/devinstevenson)
178
+ * New metrics tail-ratio and common sense ratio
179
+ [PR276](https://github.com/quantopian/pyfolio/pull/276). [Thomas
180
+ Wiecki](https://github.com/twiecki)
181
+ * Log-scaled cumulative returns plot and raw returns plot
182
+ [PR294](https://github.com/quantopian/pyfolio/pull/294). [Thomas
183
+ Wiecki](https://github.com/twiecki)
184
+
185
+ ### Bug fixes
186
+ * Many depracation fixes for Pandas 0.18.0, seaborn 0.6.0, and zipline 0.8.4
187
+
188
+
189
+ ## v0.4.0 (Dec 10, 2015)
190
+
191
+ This is a major release from 0.3.1 that includes new features and quite a few bug fixes. We recommend that all users upgrade to this new version.
192
+
193
+ ### New features
194
+
195
+ * Round-trip analysis [PR210](https://github.com/quantopian/pyfolio/pull/210)
196
+ Andrew, Thomas
197
+ * Improved cone to forecast returns that uses a bootstrap instead of linear
198
+ forecasting [PR233](https://github.com/quantopian/pyfolio/pull/233) Andrew,
199
+ Thomas
200
+ * Plot max and median long/short exposures
201
+ [PR237](https://github.com/quantopian/pyfolio/pull/237) Andrew
202
+
203
+ ### Bug fixes
204
+
205
+ * Sharpe ratio was calculated incorrectly
206
+ [PR219](https://github.com/quantopian/pyfolio/pull/219) Thomas, Justin
207
+ * annual_return() now only computes CAGR in the correct way
208
+ [PR234](https://github.com/quantopian/pyfolio/pull/234) Justin
209
+ * Cache SPY and Fama-French returns in home-directory instead of
210
+ install-directory [PR241](https://github.com/quantopian/pyfolio/pull/241) Joe
211
+ * Remove data files from package
212
+ [PR241](https://github.com/quantopian/pyfolio/pull/241) Joe
213
+ * Cast factor.name to str
214
+ [PR223](https://github.com/quantopian/pyfolio/pull/223) Scotty
215
+ * Test all `create_*_tear_sheet` functions in all configurations
216
+ [PR247](https://github.com/quantopian/pyfolio/pull/247) Thomas
217
+
218
+
219
+ ## v0.3.1 (Nov 12, 2015)
220
+
221
+ This is a minor release from 0.3 that includes mostly bugfixes but also some new features. We recommend that all users upgrade to this new version.
222
+
223
+ ### New features
224
+
225
+ * Add Information Ratio [PR194](https://github.com/quantopian/pyfolio/pull/194)
226
+ by @MridulS
227
+ * Bayesian tear-sheet now accepts 'Fama-French' option to do Bayesian
228
+ multivariate regression against Fama-French risk factors
229
+ [PR200](https://github.com/quantopian/pyfolio/pull/200) by Shane Bussman
230
+ * Plotting of monthly returns
231
+ [PR195](https://github.com/quantopian/pyfolio/pull/195)
232
+
233
+ ### Bug fixes
234
+
235
+ * `pos.get_percent_alloc` was not handling short allocations correctly
236
+ [PR201](https://github.com/quantopian/pyfolio/pull/201)
237
+ * UTC bug with cached Fama-French factors
238
+ [commit](https://github.com/quantopian/pyfolio/commit/709553a55b5df7c908d17f443cb17b51854a65be)
239
+ * Sector map was not being passed from `create_returns_tearsheet`
240
+ [commit](https://github.com/quantopian/pyfolio/commit/894b753e365f9cb4861ffca2ef214c5a64b2bef4)
241
+ * New sector mapping feature was not Python 3 compatible
242
+ [PR201](https://github.com/quantopian/pyfolio/pull/201)
243
+
244
+
245
+ ### Maintenance
246
+
247
+ * We now depend on pandas-datareader as the yahoo finance loaders from pandas
248
+ will be deprecated [PR181](https://github.com/quantopian/pyfolio/pull/181) by
249
+ @tswrightsandpointe
250
+
251
+ ### Contributors
252
+
253
+ Besiders the core developers, we have seen an increase in outside contributions
254
+ which we greatly appreciate. Specifically, these people contributed to this
255
+ release:
256
+
257
+ * Shane Bussman
258
+ * @MridulS
259
+ * @YihaoLu
260
+ * @jkrauss82
261
+ * @tswrightsandpointe
262
+ * @cgdeboer
263
+
264
+
265
+ ## v0.3 (Oct 23, 2015)
266
+
267
+ This is a major release from 0.2 that includes many exciting new features. We
268
+ recommend that all users upgrade to this new version.
269
+
270
+ ### New features
271
+
272
+ * Sector exposures: sum positions by sector given a dictionary or series of
273
+ symbol to sector mappings
274
+ [PR166](https://github.com/quantopian/pyfolio/pull/166)
275
+ * Ability to make cones with multiple shades stdev regions
276
+ [PR168](https://github.com/quantopian/pyfolio/pull/168)
277
+ * Slippage sweep: See how an algorithm performs with various levels of slippage
278
+ [PR170](https://github.com/quantopian/pyfolio/pull/170)
279
+ * Stochastic volatility model in Bayesian tear sheet
280
+ [PR174](https://github.com/quantopian/pyfolio/pull/174)
281
+ * Ability to suppress display of position information
282
+ [PR177](https://github.com/quantopian/pyfolio/pull/177)
283
+
284
+ ### Bug fixes
285
+
286
+ * Various fixes to make pyfolio pandas 0.17 compatible
287
+
288
+ ## v0.2 (Oct 16, 2015)
289
+
290
+ This is a major release from 0.1 that includes mainly bugfixes and refactorings
291
+ but also some new features. We recommend that all users upgrade to this new
292
+ version.
293
+
294
+ ### New features
295
+
296
+ * Volatility matched cumulative returns plot
297
+ [PR126](https://github.com/quantopian/pyfolio/pull/126).
298
+ * Allow for different periodicity (annualization factors) in the annual_()
299
+ methods [PR164](https://github.com/quantopian/pyfolio/pull/164).
300
+ * Users can supply their own interesting periods
301
+ [PR163](https://github.com/quantopian/pyfolio/pull/163).
302
+ * Ability to weight a portfolio of holdings by a metric valued
303
+ [PR161](https://github.com/quantopian/pyfolio/pull/161).
304
+
305
+ ### Bug fixes
306
+
307
+ * Fix drawdown overlaps [PR150](https://github.com/quantopian/pyfolio/pull/150).
308
+ * Monthly returns distribution should not stack by year
309
+ [PR162](https://github.com/quantopian/pyfolio/pull/162).
310
+ * Fix gross leverage [PR147](https://github.com/quantopian/pyfolio/pull/147)
pyfolio/source/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ pyfolio Project Package Initialization File
4
+ """
pyfolio/source/build_and_deploy_docs.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ pushd docs
4
+ bash convert_nbs_to_md.sh
5
+ popd
6
+ mkdocs build --clean
7
+ mkdocs gh-deploy
pyfolio/source/conda/bld.bat ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ "%PYTHON%" setup.py install
2
+ if errorlevel 1 exit 1
3
+
4
+ :: Add more build steps here, if they are necessary.
5
+
6
+ :: See
7
+ :: http://docs.continuum.io/conda/build.html
8
+ :: for a list of environment variables that are set during the build process.
pyfolio/source/conda/build.sh ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ $PYTHON setup.py install --single-version-externally-managed --record=record.txt
4
+
5
+ # Add more build steps here, if they are necessary.
6
+
7
+ # See
8
+ # http://docs.continuum.io/conda/build.html
9
+ # for a list of environment variables that are set during the build process.
pyfolio/source/conda/meta.yaml ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package:
2
+ name: pyfolio
3
+ version: "0.6.0"
4
+
5
+ source:
6
+ fn: pyfolio-0.6.0.tar.gz
7
+ url: https://pypi.python.org/packages/74/b6/bd9064f071ab71312256dc0dcf792440f2e41a66f6736bd2aa90ba965fb6/pyfolio-0.6.0.tar.gz#md5=f3f02df1c1b77209eb33c64e34f00031
8
+ md5: f3f02df1c1b77209eb33c64e34f00031
9
+
10
+ build:
11
+ noarch_python: True
12
+
13
+ requirements:
14
+ build:
15
+ - python
16
+ - setuptools
17
+
18
+ run:
19
+ - python
20
+ - matplotlib >=1.4.0
21
+ - numpy >=1.9.1
22
+ - pandas >=0.18.0
23
+ - pytz >=2014.10
24
+ - scipy >=0.14.0
25
+ - seaborn >=0.6.0
26
+ - pandas-datareader >=0.2
27
+ - ipython
28
+ - empyrical >=0.2.1
29
+
30
+ test:
31
+ # Python imports
32
+ imports:
33
+ - pyfolio
34
+ - pyfolio.tests
35
+
36
+ #commands:
37
+ # - nosetests # You can put test commands to be run here. Use this to test that the
38
+ # # entry points work.
39
+
40
+ about:
41
+ home: http://quantopian.github.io/pyfolio/
42
+ license: Apache Software License
43
+ summary: 'pyfolio is a Python library for performance and risk analysis of financial portfolios'
pyfolio/source/docs/convert_nbs_to_md.sh ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ NBDIR=notebooks
3
+
4
+ for fullfile in $NBDIR/*.ipynb; do
5
+ echo "Processing $fullfile file..";
6
+ filename=$(basename "$fullfile")
7
+ extension="${filename##*.}"
8
+ filename="${filename%.*}"
9
+ jupyter nbconvert $fullfile --to markdown --output $filename
10
+ done
pyfolio/source/docs/example_tear_0.png ADDED
pyfolio/source/docs/example_tear_1.png ADDED

Git LFS Details

  • SHA256: be963f3c1dfd4c8e59a2feb37b85fcec158036c5564478abc9e8df1d2aa01d49
  • Pointer size: 131 Bytes
  • Size of remote file: 557 kB
pyfolio/source/docs/extra.css ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ img[title="pyfolio"] {
2
+ background-color: transparent !important;
3
+ border: 0 !important;
4
+ }
pyfolio/source/docs/index.md ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ![pyfolio](https://media.quantopian.com/logos/open_source/pyfolio-logo-03.png "pyfolio")
2
+
3
+ # pyfolio
4
+
5
+ [![Join the chat at https://gitter.im/quantopian/pyfolio](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/quantopian/pyfolio?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
6
+ [![build status](https://travis-ci.org/quantopian/pyfolio.png?branch=master)](https://travis-ci.org/quantopian/pyfolio)
7
+
8
+ pyfolio is a Python library for performance and risk analysis of
9
+ financial portfolios developed by
10
+ [Quantopian Inc](https://www.quantopian.com). It works well with the
11
+ [Zipline](https://www.zipline.io/) open source backtesting library.
12
+ Quantopian also offers a [fully managed service for professionals](https://factset.quantopian.com)
13
+ that includes Zipline, Alphalens, Pyfolio, FactSet data, and more.
14
+
15
+ At the core of pyfolio is a so-called tear sheet that consists of
16
+ various individual plots that provide a comprehensive image of the
17
+ performance of a trading algorithm. Here's an example of a simple tear
18
+ sheet analyzing a strategy:
19
+
20
+ ![simple tear 0](https://github.com/quantopian/pyfolio/raw/master/docs/simple_tear_0.png "Example tear sheet created from a Zipline algo")
21
+ ![simple tear 1](https://github.com/quantopian/pyfolio/raw/master/docs/simple_tear_1.png "Example tear sheet created from a Zipline algo")
22
+
23
+ Also see [slides of a talk about
24
+ pyfolio](https://nbviewer.jupyter.org/format/slides/github/quantopian/pyfolio/blob/master/pyfolio/examples/pyfolio_talk_slides.ipynb#/).
25
+
26
+ ## Installation
27
+
28
+ To install pyfolio, run:
29
+
30
+ ```bash
31
+ pip install pyfolio
32
+ ```
33
+
34
+ #### Development
35
+
36
+ For development, you may want to use a [virtual environment](https://docs.python-guide.org/en/latest/dev/virtualenvs/) to avoid dependency conflicts between pyfolio and other Python projects you have. To get set up with a virtual env, run:
37
+ ```bash
38
+ mkvirtualenv pyfolio
39
+ ```
40
+
41
+ Next, clone this git repository and run `python setup.py develop`
42
+ and edit the library files directly.
43
+
44
+ #### Matplotlib on OSX
45
+
46
+ If you are on OSX and using a non-framework build of Python, you may need to set your backend:
47
+ ``` bash
48
+ echo "backend: TkAgg" > ~/.matplotlib/matplotlibrc
49
+ ```
50
+
51
+ ## Usage
52
+
53
+ A good way to get started is to run the pyfolio examples in
54
+ a [Jupyter notebook](https://jupyter.org/). To do this, you first want to
55
+ start a Jupyter notebook server:
56
+
57
+ ```bash
58
+ jupyter notebook
59
+ ```
60
+
61
+ From the notebook list page, navigate to the pyfolio examples directory
62
+ and open a notebook. Execute the code in a notebook cell by clicking on it
63
+ and hitting Shift+Enter.
64
+
65
+
66
+ ## Questions?
67
+
68
+ If you find a bug, feel free to [open an issue](https://github.com/quantopian/pyfolio/issues) in this repository.
69
+
70
+ You can also join our [mailing list](https://groups.google.com/forum/#!forum/pyfolio) or
71
+ our [Gitter channel](https://gitter.im/quantopian/pyfolio).
72
+
73
+ ## Support
74
+
75
+ Please [open an issue](https://github.com/quantopian/pyfolio/issues/new) for support.
76
+
77
+ ## Contributing
78
+
79
+ If you'd like to contribute, a great place to look is the [issues marked with help-wanted](https://github.com/quantopian/pyfolio/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22).
80
+
81
+ For a list of core developers and outside collaborators, see [the GitHub contributors list](https://github.com/quantopian/pyfolio/graphs/contributors).
pyfolio/source/docs/notebooks/fama_french_benchmark.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
pyfolio/source/docs/notebooks/full_tear_sheet_example.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
pyfolio/source/docs/notebooks/round_trip_tear_sheet_example.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
pyfolio/source/docs/notebooks/sector_mappings_example.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
pyfolio/source/docs/notebooks/single_stock_example.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
pyfolio/source/docs/notebooks/slippage_example.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
pyfolio/source/docs/notebooks/zipline_algo_example.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
pyfolio/source/docs/simple_tear_0.png ADDED
pyfolio/source/docs/simple_tear_1.png ADDED

Git LFS Details

  • SHA256: a4144778758c67162061c58e2b5250cbfa06f9c2f6708983dcf77d84422f21a3
  • Pointer size: 131 Bytes
  • Size of remote file: 521 kB
pyfolio/source/docs/whatsnew.md ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # What's New
2
+
3
+ These are new features and improvements of note in each release.
4
+
5
+ ## v0.9.0 (Aug 1st, 2018)
6
+
7
+ ### New features
8
+
9
+ - Previously, `pyfolio` has required a benchmark, usually the U.S. market
10
+ returns `SPY`. In order to provide support for international equities and
11
+ alternative data sets, `pyfolio` is now completely independent of benchmarks.
12
+ If a benchmark is passed, all benchmark-related analyses will be performed;
13
+ if not, they will simply be skipped. By [George Ho](https://github.com/eigenfoo)
14
+ - Performance attribution tearsheet [PR441](https://github.com/quantopian/pyfolio/pull/441), [PR433](https://github.com/quantopian/pyfolio/pull/433), [PR442](https://github.com/quantopian/pyfolio/pull/442). By [Vikram Narayan](https://github.com/vikram-narayan).
15
+ - Improved implementation of `get_turnover` [PR332](https://github.com/quantopian/pyfolio/pull/432). By [Gus Gordon](https://github.com/gusgordon).
16
+ - Users can now pass in extra rows (as a dict or OrderedDict) to display in the perf_stats table [PR445](https://github.com/quantopian/pyfolio/pull/445). By [Gus Gordon](https://github.com/gusgordon).
17
+
18
+ ### Maintenance
19
+
20
+ - Many features have been more extensively troubleshooted, maintained and
21
+ tested. By [Ana Ruelas](https://github.com/ahgnaw) and [Vikram
22
+ Narayan](https://github.com/vikram-narayan).
23
+ - Various fixes to support pandas versions >= 0.18.1 [PR443](https://github.com/quantopian/pyfolio/pull/443). By [Andrew Daniels](https://github.com/yankees714).
24
+
25
+ ## v0.8.0 (Aug 23rd, 2017)
26
+
27
+ This is a major release from `0.7.0`, and all users are recommended to upgrade.
28
+
29
+ ### New features
30
+
31
+ - Risk tear sheet: added a new tear sheet to analyze risk exposures to common
32
+ factors (e.g. mean reversion and momentum), sector (e.g. Morningstar
33
+ sectors), market cap and illiquid stocks. By [George
34
+ Ho](https://github.com/eigenfoo).
35
+ - Simple tear sheet: added a new tear sheet that presents only the most
36
+ important plots in the full tear sheet, for a quick general overview of a
37
+ portfolio's performance. By [George Ho](https://github.com/eigenfoo).
38
+ - Performance attribution: added new table to do performance attribution
39
+ analysis, such as the amount of returns attributable to common factors, and
40
+ summary statistics such as the multi-factor alpha and multi-factor Sharpe
41
+ ratio. By [Vikram Narayan](https://github.com/vikram-narayan).
42
+ - Volatility plot: added a rolling annual volatility plot to the returns tear
43
+ sheet. By [hkopp](https://github.com/hkopp).
44
+
45
+ ### Bugfixes
46
+
47
+ - Yahoo and pandas data-reader: fixed bug regarding Yahoo backend for market
48
+ data and pandas data-reader. By [Thomas Wiecki](https://github.com/twiecki)
49
+ and [Gus Gordon](https://github.com/gusgordon).
50
+ - `empyrical` compatibility: removed `information_ratio` to remain compatible
51
+ with `empyrical`. By [Thomas Wiecki](https://github.com/twiecki).
52
+ - Fama-French rolling multivariate regression: fixed bug where the rolling
53
+ Fama-French plot performed separate linear regressions instead of a
54
+ multivariate regression. By [George Ho](https://github.com/eigenfoo).
55
+ - Other minor bugfixes. By [Scott Sanderson](https://github.com/ssanderson),
56
+ [Jonathan Ng](https://github.com/jonathanng),
57
+ [SylvainDe](https://github.com/SylvainDe) and
58
+ [mckelvin](https://github.com/mckelvin).
59
+
60
+ ### Maintenance
61
+
62
+ - Documentation: updated and improved `pyfolio` documentation and example
63
+ Jupyter notebooks. By [George Ho](https://github.com/eigenfoo).
64
+ - Data loader migration: all data loaders have been migrated from `pyfolio` to
65
+ `empyrical`. By [James Christopher](https://github.com/jameschristopher).
66
+ - Improved plotting style: fixed issues with formatting and presentation of
67
+ plots. By [George Ho](https://github.com/eigenfoo).
68
+
69
+ ## v0.7.0 (Jan 28th, 2017)
70
+
71
+ This is a major release from `0.6.0`, and all users are recommended to upgrade.
72
+
73
+ ### New features
74
+
75
+ - Adds a transaction timing plot, which gives insight into the strategies'
76
+ trade times.
77
+ - Adds a plot showing the number of longs and shorts held over time.
78
+ - New round trips plot selects a sample of held positions (16 by default) and
79
+ shows their round trips. This replaces the old round trip plot, which became
80
+ unreadable for strategies that traded many positions.
81
+ - Adds basic capability for analyzing intraday strategies. If a strategy makes
82
+ a large amount of transactions relative to its end-of-day positions, then
83
+ pyfolio will attempt to reconstruct the intraday positions, take the point of
84
+ peak exposure to the market during each day, and plot that data with the
85
+ positions tear sheet. By default pyfolio will automatically detect this, but
86
+ the behavior can be changed by passing either `estimate_intraday=True` or
87
+ `estimate_intraday=False` to the tear sheet functions ([see
88
+ here](https://github.com/quantopian/pyfolio/blob/master/pyfolio/tears.py#L131)).
89
+ - Now formats [zipline](https://github.com/quantopian/zipline) assets,
90
+ displaying their ticker symbol.
91
+ - Gross leverage is no longer required to be passed, and will now be calculated
92
+ from the passed positions DataFrame.
93
+
94
+ ### Bugfixes
95
+
96
+ - Cone plotting location is now correct.
97
+ - Adjust scaling of beta and Fama-French plots.
98
+ - Removed multiple dependencies, some of which were previously unused.
99
+ - Various text fixes.
100
+
101
+ ## v0.6.0 (Oct 17, 2016)
102
+
103
+ This is a major new release from `0.5.1`. All users are recommended to upgrade.
104
+
105
+ ### New features
106
+
107
+ * Computation of performance and risk measures has been split off into
108
+ [`empyrical`](https://github.com/quantopian/empyrical). This allows
109
+ [`Zipline`](https://zipline.io) and `pyfolio` to use the same code to
110
+ calculate its risk statistics. By [Ana Ruelas](https://github.com/ahgnaw) and
111
+ [Abhi Kalyan](https://github.com/abhijeetkalyan).
112
+ * New multistrike cone which redraws the cone when it crossed its initial bounds
113
+ [PR310](https://github.com/quantopian/pyfolio/pull/310). By [Ana
114
+ Ruelas](https://github.com/ahgnaw) and [Abhi
115
+ Kalyan](https://github.com/abhijeetkalyan).
116
+
117
+ ### Bugfixes
118
+
119
+ * Can use most recent PyMC3 now.
120
+ * Depends on seaborn 0.7.0 or later now
121
+ [PR331](https://github.com/quantopian/pyfolio/pull/331).
122
+ * Disable buggy computation of round trips per day and per month
123
+ [PR339](https://github.com/quantopian/pyfolio/pull/339).
124
+
125
+ ## v0.5.1 (June 10, 2016)
126
+
127
+ This is a bugfix release from `0.5.0` with limited new functionality. All users are recommended to upgrade.
128
+
129
+ ### New features
130
+
131
+ * OOS data is now overlaid on top of box plot
132
+ [PR306](https://github.com/quantopian/pyfolio/pull/306) by [Ana
133
+ Ruelas](https://github.com/ahgnaw)
134
+ * New logo [PR298](https://github.com/quantopian/pyfolio/pull/298) by [Taso
135
+ Petridis](https://github.com/tasopetridis) and [Richard
136
+ Frank](https://github.com/richafrank)
137
+ * Raw returns plot and cumulative log returns plot
138
+ [PR294](https://github.com/quantopian/pyfolio/pull/294) by [Thomas
139
+ Wiecki](https://github.com/twiecki)
140
+ * Net exposure line to the long/short exposure plot
141
+ [PR301](https://github.com/quantopian/pyfolio/pull/301) by [Ana
142
+ Ruelas](https://github.com/ahgnaw)
143
+
144
+ ### Bugfixes
145
+
146
+ * Fix drawdown behavior and pandas exception in tear-sheet creation
147
+ [PR297](https://github.com/quantopian/pyfolio/pull/297) by [Flavio
148
+ Duarte](https://github.com/flaviodrt)
149
+
150
+ ## v0.5.0 (April 21, 2016) -- Olympia
151
+
152
+ This is a major release from `0.4.0` that includes many new analyses and
153
+ features. We recommend that all users upgrade to this new version. Also update
154
+ your dependencies, specifically, `pandas>=0.18.0`, `seaborn>=0.6.0` and
155
+ `zipline>=0.8.4`.
156
+
157
+ ### New features
158
+
159
+ * New capacity tear-sheet to assess how much capital can be traded on a strategy
160
+ [PR284](https://github.com/quantopian/pyfolio/pull/284). [Andrew
161
+ Campbell](https://github.com/a-campbell).
162
+ * Bootstrap analysis to assess uncertainty in performance metrics
163
+ [PR261](https://github.com/quantopian/pyfolio/pull/261). [Thomas
164
+ Wiecki](https://github.com/twiecki)
165
+ * Refactored round-trip analysis to be more general and have better output. Now
166
+ does full portfolio reconstruction to match trades
167
+ [PR293](https://github.com/quantopian/pyfolio/pull/293). [Thomas
168
+ Wiecki](https://github.com/twiecki), [Andrew
169
+ Campbell](https://github.com/a-campbell). See the
170
+ [tutorial](http://quantopian.github.io/pyfolio/round_trip_example/) for more
171
+ information.
172
+ * Prettier printing of tables in notebooks
173
+ [PR289](https://github.com/quantopian/pyfolio/pull/289). [Thomas
174
+ Wiecki](https://github.com/twiecki)
175
+ * Faster max-drawdown calculation
176
+ [PR281](https://github.com/quantopian/pyfolio/pull/281). [Devin
177
+ Stevenson](https://github.com/devinstevenson)
178
+ * New metrics tail-ratio and common sense ratio
179
+ [PR276](https://github.com/quantopian/pyfolio/pull/276). [Thomas
180
+ Wiecki](https://github.com/twiecki)
181
+ * Log-scaled cumulative returns plot and raw returns plot
182
+ [PR294](https://github.com/quantopian/pyfolio/pull/294). [Thomas
183
+ Wiecki](https://github.com/twiecki)
184
+
185
+ ### Bug fixes
186
+ * Many depracation fixes for Pandas 0.18.0, seaborn 0.6.0, and zipline 0.8.4
187
+
188
+
189
+ ## v0.4.0 (Dec 10, 2015)
190
+
191
+ This is a major release from 0.3.1 that includes new features and quite a few bug fixes. We recommend that all users upgrade to this new version.
192
+
193
+ ### New features
194
+
195
+ * Round-trip analysis [PR210](https://github.com/quantopian/pyfolio/pull/210)
196
+ Andrew, Thomas
197
+ * Improved cone to forecast returns that uses a bootstrap instead of linear
198
+ forecasting [PR233](https://github.com/quantopian/pyfolio/pull/233) Andrew,
199
+ Thomas
200
+ * Plot max and median long/short exposures
201
+ [PR237](https://github.com/quantopian/pyfolio/pull/237) Andrew
202
+
203
+ ### Bug fixes
204
+
205
+ * Sharpe ratio was calculated incorrectly
206
+ [PR219](https://github.com/quantopian/pyfolio/pull/219) Thomas, Justin
207
+ * annual_return() now only computes CAGR in the correct way
208
+ [PR234](https://github.com/quantopian/pyfolio/pull/234) Justin
209
+ * Cache SPY and Fama-French returns in home-directory instead of
210
+ install-directory [PR241](https://github.com/quantopian/pyfolio/pull/241) Joe
211
+ * Remove data files from package
212
+ [PR241](https://github.com/quantopian/pyfolio/pull/241) Joe
213
+ * Cast factor.name to str
214
+ [PR223](https://github.com/quantopian/pyfolio/pull/223) Scotty
215
+ * Test all `create_*_tear_sheet` functions in all configurations
216
+ [PR247](https://github.com/quantopian/pyfolio/pull/247) Thomas
217
+
218
+
219
+ ## v0.3.1 (Nov 12, 2015)
220
+
221
+ This is a minor release from 0.3 that includes mostly bugfixes but also some new features. We recommend that all users upgrade to this new version.
222
+
223
+ ### New features
224
+
225
+ * Add Information Ratio [PR194](https://github.com/quantopian/pyfolio/pull/194)
226
+ by @MridulS
227
+ * Bayesian tear-sheet now accepts 'Fama-French' option to do Bayesian
228
+ multivariate regression against Fama-French risk factors
229
+ [PR200](https://github.com/quantopian/pyfolio/pull/200) by Shane Bussman
230
+ * Plotting of monthly returns
231
+ [PR195](https://github.com/quantopian/pyfolio/pull/195)
232
+
233
+ ### Bug fixes
234
+
235
+ * `pos.get_percent_alloc` was not handling short allocations correctly
236
+ [PR201](https://github.com/quantopian/pyfolio/pull/201)
237
+ * UTC bug with cached Fama-French factors
238
+ [commit](https://github.com/quantopian/pyfolio/commit/709553a55b5df7c908d17f443cb17b51854a65be)
239
+ * Sector map was not being passed from `create_returns_tearsheet`
240
+ [commit](https://github.com/quantopian/pyfolio/commit/894b753e365f9cb4861ffca2ef214c5a64b2bef4)
241
+ * New sector mapping feature was not Python 3 compatible
242
+ [PR201](https://github.com/quantopian/pyfolio/pull/201)
243
+
244
+
245
+ ### Maintenance
246
+
247
+ * We now depend on pandas-datareader as the yahoo finance loaders from pandas
248
+ will be deprecated [PR181](https://github.com/quantopian/pyfolio/pull/181) by
249
+ @tswrightsandpointe
250
+
251
+ ### Contributors
252
+
253
+ Besiders the core developers, we have seen an increase in outside contributions
254
+ which we greatly appreciate. Specifically, these people contributed to this
255
+ release:
256
+
257
+ * Shane Bussman
258
+ * @MridulS
259
+ * @YihaoLu
260
+ * @jkrauss82
261
+ * @tswrightsandpointe
262
+ * @cgdeboer
263
+
264
+
265
+ ## v0.3 (Oct 23, 2015)
266
+
267
+ This is a major release from 0.2 that includes many exciting new features. We
268
+ recommend that all users upgrade to this new version.
269
+
270
+ ### New features
271
+
272
+ * Sector exposures: sum positions by sector given a dictionary or series of
273
+ symbol to sector mappings
274
+ [PR166](https://github.com/quantopian/pyfolio/pull/166)
275
+ * Ability to make cones with multiple shades stdev regions
276
+ [PR168](https://github.com/quantopian/pyfolio/pull/168)
277
+ * Slippage sweep: See how an algorithm performs with various levels of slippage
278
+ [PR170](https://github.com/quantopian/pyfolio/pull/170)
279
+ * Stochastic volatility model in Bayesian tear sheet
280
+ [PR174](https://github.com/quantopian/pyfolio/pull/174)
281
+ * Ability to suppress display of position information
282
+ [PR177](https://github.com/quantopian/pyfolio/pull/177)
283
+
284
+ ### Bug fixes
285
+
286
+ * Various fixes to make pyfolio pandas 0.17 compatible
287
+
288
+ ## v0.2 (Oct 16, 2015)
289
+
290
+ This is a major release from 0.1 that includes mainly bugfixes and refactorings
291
+ but also some new features. We recommend that all users upgrade to this new
292
+ version.
293
+
294
+ ### New features
295
+
296
+ * Volatility matched cumulative returns plot
297
+ [PR126](https://github.com/quantopian/pyfolio/pull/126).
298
+ * Allow for different periodicity (annualization factors) in the annual_()
299
+ methods [PR164](https://github.com/quantopian/pyfolio/pull/164).
300
+ * Users can supply their own interesting periods
301
+ [PR163](https://github.com/quantopian/pyfolio/pull/163).
302
+ * Ability to weight a portfolio of holdings by a metric valued
303
+ [PR161](https://github.com/quantopian/pyfolio/pull/161).
304
+
305
+ ### Bug fixes
306
+
307
+ * Fix drawdown overlaps [PR150](https://github.com/quantopian/pyfolio/pull/150).
308
+ * Monthly returns distribution should not stack by year
309
+ [PR162](https://github.com/quantopian/pyfolio/pull/162).
310
+ * Fix gross leverage [PR147](https://github.com/quantopian/pyfolio/pull/147)
pyfolio/source/mkdocs.yml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ site_name: pyfolio
2
+ repo_url: https://github.com/quantopian/pyfolio
3
+ site_author: Quantopian Inc.
4
+
5
+ pages:
6
+ - Overview: 'index.md'
7
+ - Releases: 'whatsnew.md'
8
+ - Tutorial:
9
+ - 'Single stock': 'notebooks/single_stock_example.md'
10
+ - 'Zipline algorithm': 'notebooks/zipline_algo_example.md'
11
+ - 'Sector analysis': 'notebooks/sector_mappings_example.md'
12
+ - 'Round trip analysis': 'notebooks/round_trip_tear_sheet_example.md'
13
+ - 'Slippage analysis': 'notebooks/slippage_example.md'
14
+
15
+ extra_css: [extra.css]
pyfolio/source/pyfolio/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import utils
2
+ from . import timeseries
3
+ from . import pos
4
+ from . import txn
5
+ from . import interesting_periods
6
+ from . import capacity
7
+ from . import round_trips
8
+ from . import perf_attrib
9
+
10
+ from .tears import * # noqa
11
+ from .plotting import * # noqa
12
+ from ._version import get_versions
13
+
14
+ __version__ = get_versions()['version']
15
+ del get_versions
16
+
17
+ __all__ = ['utils', 'timeseries', 'pos', 'txn',
18
+ 'interesting_periods', 'capacity', 'round_trips',
19
+ 'perf_attrib']
pyfolio/source/pyfolio/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (650 Bytes). View file
 
pyfolio/source/pyfolio/__pycache__/utils.cpython-310.pyc ADDED
Binary file (14.3 kB). View file
 
pyfolio/source/pyfolio/_seaborn.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Wrapper module around seaborn to suppress warnings on import.
2
+
3
+ This should be removed when seaborn stops raising:
4
+
5
+ UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle;
6
+ please use the latter.
7
+ """
8
+ import warnings
9
+
10
+
11
+ with warnings.catch_warnings():
12
+ warnings.filterwarnings(
13
+ 'ignore',
14
+ 'axes.color_cycle is deprecated',
15
+ UserWarning,
16
+ 'matplotlib',
17
+ )
18
+ from seaborn import * # noqa