jimchoi commited on
Commit
5e25eba
·
verified ·
1 Parent(s): 59649d7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -30
app.py CHANGED
@@ -33,43 +33,60 @@ def get_current_time_in_timezone(timezone: str) -> str:
33
  except Exception as e:
34
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
35
 
36
-
37
- import requests
38
- from bs4 import BeautifulSoup
39
-
40
  @tool
41
- def get_stock_data(stock_code: str) -> str:
42
- """A tool that fetches the latest stock data for a given stock code from East Money website.
43
  Args:
44
- stock_code: A string representing the stock code (e.g., 'SH600000' for Shanghai Pudong Development Bank).
45
  """
46
  try:
47
- # Construct the URL for the stock data
48
- url = f"https://quote.eastmoney.com/{stock_code}.html"
49
-
50
- # Send a GET request to the URL
51
- response = requests.get(url)
52
- response.raise_for_status() # Raise an error for bad status codes
53
-
54
- # Parse the HTML content using BeautifulSoup
55
- soup = BeautifulSoup(response.text, 'html.parser')
56
-
57
- # Extract the stock name
58
- stock_name = soup.find('div', class_='stock-name').text.strip()
59
-
60
- # Extract the current price
61
- current_price = soup.find('div', class_='stock-current').text.strip()
62
-
63
- # Extract the change in price and percentage
64
- price_change = soup.find('div', class_='stock-change').text.strip()
65
- change_percentage = soup.find('div', class_='stock-change-percent').text.strip()
66
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  # Construct the result string
68
- result = f"Stock: {stock_name}\nCurrent Price: {current_price}\nChange: {price_change} ({change_percentage})"
69
-
70
  return result
 
71
  except Exception as e:
72
- return f"Error fetching stock data for code '{stock_code}': {str(e)}"
 
 
 
 
73
 
74
 
75
  final_answer = FinalAnswerTool()
 
33
  except Exception as e:
34
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
35
 
36
+ import baostock as bs
37
+ import pandas as pd
 
 
38
  @tool
39
+ def get_stock_data_baostock(stock_code: str) -> str:
40
+ """Fetch the latest stock data for a given stock code using Baostock.
41
  Args:
42
+ stock_code: A string representing the stock code (e.g., 'sh.600941' for China Mobile).
43
  """
44
  try:
45
+ # Log in to the Baostock system
46
+ lg = bs.login()
47
+ if lg.error_code != '0':
48
+ return f"Failed to log in to Baostock: {lg.error_msg}"
49
+
50
+ # Fetch daily K-line data for the stock (defaults to the most recent trading day)
51
+ rs = bs.query_history_k_data_plus(
52
+ code=stock_code,
53
+ fields="date,code,open,high,low,close,volume", # Fields to retrieve
54
+ frequency="d", # Daily K-line
55
+ adjustflag="2" # Adjustment type: 2 for forward adjustment
56
+ )
57
+ if rs.error_code != '0':
58
+ return f"Failed to fetch stock data: {rs.error_msg}"
59
+
60
+ # Convert the data to a DataFrame
61
+ data_list = []
62
+ while (rs.error_code == '0') & rs.next():
63
+ data_list.append(rs.get_row_data())
64
+ df = pd.DataFrame(data_list, columns=rs.fields)
65
+
66
+ # Log out of the Baostock system
67
+ bs.logout()
68
+
69
+ # Check if the data is empty
70
+ if df.empty:
71
+ return f"No data found for stock code '{stock_code}'."
72
+
73
+ # Extract the latest trading day's data
74
+ latest_data = df.iloc[-1] # Get the last row of data (most recent trading day)
75
+ date = latest_data['date'] # Date
76
+ stock_name = latest_data['code'] # Stock code
77
+ close_price = latest_data['close'] # Closing price
78
+ volume = latest_data['volume'] # Trading volume
79
+
80
  # Construct the result string
81
+ result = f"Stock Code: {stock_name}\nDate: {date}\nClosing Price: {close_price}\nVolume: {volume}"
 
82
  return result
83
+
84
  except Exception as e:
85
+ return f"An error occurred while fetching stock data: {str(e)}"
86
+
87
+ # Example call
88
+ print(get_stock_data_baostock('sh.600941'))
89
+
90
 
91
 
92
  final_answer = FinalAnswerTool()