guohanghui commited on
Commit
aa2a38c
·
verified ·
1 Parent(s): b787e73

Update pyfolio/mcp_output/mcp_plugin/mcp_service.py

Browse files
pyfolio/mcp_output/mcp_plugin/mcp_service.py CHANGED
@@ -37,34 +37,39 @@ from pyfolio.plotting import (
37
 
38
  mcp = FastMCP("pyfolio_service")
39
 
40
- def _save_plot_as_base64(fig=None, filename_prefix="plot") -> str:
41
- """Save matplotlib plot as base64 encoded image."""
42
- try:
43
- if fig is None:
44
- fig = plt.gcf()
45
-
46
- # Save to BytesIO
47
- buffer = io.BytesIO()
48
- fig.savefig(buffer, format='png', dpi=150, bbox_inches='tight')
49
- buffer.seek(0)
50
-
51
- # Convert to base64
52
- image_base64 = base64.b64encode(buffer.getvalue()).decode('utf-8')
53
-
54
- # Also save to file
55
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
56
- filepath = f"/tmp/{filename_prefix}_{timestamp}.png"
57
- fig.savefig(filepath, format='png', dpi=150, bbox_inches='tight')
58
-
59
- plt.close(fig) # Close to free memory
60
-
61
- return {
62
- "base64": image_base64,
63
- "filepath": filepath,
64
- "data_uri": f"data:image/png;base64,{image_base64}"
65
- }
66
- except Exception as e:
67
- return {"error": str(e)}
 
 
 
 
 
68
 
69
  def _convert_to_series(data: List[float], name: str = "returns") -> pd.Series:
70
  """Convert list to pandas Series with date index."""
 
37
 
38
  mcp = FastMCP("pyfolio_service")
39
 
40
+ def _save_plot_as_base64(plt, plot_name):
41
+ """Save plot as base64 string and to file"""
42
+ import base64
43
+ from io import BytesIO
44
+ import datetime
45
+ import os
46
+
47
+ # Generate timestamp for unique filename
48
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
49
+ filename = f"{plot_name}_{timestamp}.png"
50
+
51
+ # Save to current working directory instead of /tmp
52
+ current_dir = os.getcwd()
53
+ filepath = os.path.join(current_dir, filename)
54
+
55
+ # Save to file
56
+ plt.savefig(filepath, dpi=300, bbox_inches='tight')
57
+
58
+ # Convert to base64
59
+ buffer = BytesIO()
60
+ plt.savefig(buffer, format='png', dpi=300, bbox_inches='tight')
61
+ buffer.seek(0)
62
+ image_base64 = base64.b64encode(buffer.getvalue()).decode('utf-8')
63
+ buffer.close()
64
+
65
+ # Create data URI
66
+ data_uri = f"data:image/png;base64,{image_base64}"
67
+
68
+ return {
69
+ "image_base64": image_base64,
70
+ "image_path": filepath,
71
+ "data_uri": data_uri
72
+ }
73
 
74
  def _convert_to_series(data: List[float], name: str = "returns") -> pd.Series:
75
  """Convert list to pandas Series with date index."""