akashraut commited on
Commit
cd37587
·
verified ·
1 Parent(s): 71aebe3

Update prices_server.py

Browse files
Files changed (1) hide show
  1. prices_server.py +24 -49
prices_server.py CHANGED
@@ -1,73 +1,48 @@
1
  import yfinance as yf
2
- import pandas as pd
3
  import numpy as np
 
4
  from datetime import timedelta
5
  from mcp.server.fastmcp import FastMCP
6
 
7
- # Initialize MCP server
8
  mcp = FastMCP("metal_price_server")
9
 
10
- # Yahoo Finance ticker symbols
11
- GOLD_SYMBOL = "GC=F" # Gold Futures
12
- SILVER_SYMBOL = "SI=F" # Silver Futures
13
 
14
 
15
- def get_data(symbol="XAU"):
16
- """Fetch last 15 days of price data for Gold or Silver using Yahoo Finance."""
17
  ticker_symbol = GOLD_SYMBOL if symbol == "XAU" else SILVER_SYMBOL
18
- try:
19
- ticker = yf.Ticker(ticker_symbol)
20
- hist = ticker.history(period="15d")
21
-
22
- if hist.empty:
23
- print(f"⚠️ No data returned for {ticker_symbol}")
24
- return None, None
25
-
26
- live_price = round(hist["Close"].iloc[-1], 2)
27
- return hist.reset_index(), live_price
28
-
29
- except Exception as e:
30
- print(f"❌ Error fetching data from yfinance: {e}")
31
- return None, None
32
 
33
 
34
  @mcp.tool()
35
- def get_report(symbol: str = "XAU", forecast_days: int = 3) -> str:
36
  """
37
- Generates a metal price report with recent data and forecast.
38
- symbol: 'XAU' (Gold) or 'XAG' (Silver)
39
- forecast_days: how many days ahead to predict
40
  """
41
- df_history, live_price = get_data(symbol)
42
-
43
- if df_history is None or live_price is None:
44
- return "⚠️ Could not fetch market data at this time."
45
-
46
- df = df_history.rename(columns={"Date": "date", "Close": "price"})
47
  df["day"] = np.arange(len(df))
48
- coef = np.polyfit(df["day"], df["price"], 1)
49
  model = np.poly1d(coef)
50
-
51
- future_days = np.arange(len(df), len(df) + forecast_days)
52
- predictions = model(future_days)
53
-
54
- last_date = pd.to_datetime(df["date"].iloc[-1])
55
- future_dates = [
56
- (last_date + timedelta(days=i + 1)).strftime("%Y-%m-%d")
57
- for i in range(forecast_days)
58
- ]
59
- preds = list(zip(future_dates, np.round(predictions, 2)))
60
 
61
  name = "Gold" if symbol == "XAU" else "Silver"
62
- report = f"📊 **{name} Metal Report**\n\n"
63
- report += f"**Latest Close Price:** `${live_price}` per ounce\n\n"
64
- report += "**Forecast for Next 3 Days:**\n"
65
- for date, price in preds:
66
- report += f"- {date}: `${price}`\n"
67
-
68
  return report
69
 
70
 
71
  if __name__ == "__main__":
72
- print("✅ prices_server.py (MCP + yfinance) is running...")
73
  mcp.run()
 
1
  import yfinance as yf
 
2
  import numpy as np
3
+ import pandas as pd
4
  from datetime import timedelta
5
  from mcp.server.fastmcp import FastMCP
6
 
 
7
  mcp = FastMCP("metal_price_server")
8
 
9
+ GOLD_SYMBOL = "GC=F"
10
+ SILVER_SYMBOL = "SI=F"
 
11
 
12
 
13
+ def fetch_data(symbol="XAU"):
 
14
  ticker_symbol = GOLD_SYMBOL if symbol == "XAU" else SILVER_SYMBOL
15
+ ticker = yf.Ticker(ticker_symbol)
16
+ hist = ticker.history(period="15d")
17
+ if hist.empty:
18
+ raise ValueError("No data from yfinance.")
19
+ return hist.reset_index(), round(hist["Close"].iloc[-1], 2)
 
 
 
 
 
 
 
 
 
20
 
21
 
22
  @mcp.tool()
23
+ def get_report(symbol: str = "XAU") -> str:
24
  """
25
+ Generates live price + 3-day forecast report for Gold (XAU) or Silver (XAG)
 
 
26
  """
27
+ df, live_price = fetch_data(symbol)
 
 
 
 
 
28
  df["day"] = np.arange(len(df))
29
+ coef = np.polyfit(df["day"], df["Close"], 1)
30
  model = np.poly1d(coef)
31
+ future_days = np.arange(len(df), len(df) + 3)
32
+ preds = model(future_days)
33
+ last_date = pd.to_datetime(df["Date"].iloc[-1])
34
+ future_dates = [(last_date + timedelta(days=i + 1)).strftime("%Y-%m-%d") for i in range(3)]
35
+ forecast = list(zip(future_dates, np.round(preds, 2)))
 
 
 
 
 
36
 
37
  name = "Gold" if symbol == "XAU" else "Silver"
38
+ report = f"📊 **{name} Report**\n\n"
39
+ report += f"**Live Price:** ${live_price} per ounce\n\n"
40
+ report += "**3-Day Forecast:**\n"
41
+ for date, price in forecast:
42
+ report += f"- {date}: ${price}\n"
 
43
  return report
44
 
45
 
46
  if __name__ == "__main__":
47
+ print("✅ prices_server.py running with yfinance.")
48
  mcp.run()