dure-waseem commited on
Commit
298f382
·
1 Parent(s): 6e65197

Remove chart.py from repository

Browse files
Files changed (1) hide show
  1. chart.py +0 -208
chart.py DELETED
@@ -1,208 +0,0 @@
1
- import yfinance as yf
2
- from datetime import datetime, timedelta
3
- import json
4
- import sys
5
- import os
6
- import time
7
- import requests
8
- from requests.adapters import HTTPAdapter
9
- from urllib3.util.retry import Retry
10
-
11
- def setup_session_with_retries():
12
- """Setup a requests session with retry logic for better reliability"""
13
- session = requests.Session()
14
-
15
- retry_strategy = Retry(
16
- total=3,
17
- backoff_factor=1,
18
- status_forcelist=[429, 500, 502, 503, 504],
19
- )
20
-
21
- adapter = HTTPAdapter(max_retries=retry_strategy)
22
- session.mount("http://", adapter)
23
- session.mount("https://", adapter)
24
-
25
- return session
26
-
27
- def retrieve_financial_data(company_name: str) -> str:
28
- """
29
- It returns the last 6 months of daily stock Open, High, Low, Close, Volume, Dividends, Stock Splits for the specified company.
30
-
31
- Args:
32
- company_name: str -> the ticker symbol of the company (e.g., 'AAPL', 'GOOGL')
33
-
34
- Returns:
35
- str: JSON string containing the financial data or error message
36
- """
37
- try:
38
- # Validate ticker symbol
39
- if not company_name or not company_name.strip():
40
- return "Error: Empty ticker symbol provided"
41
-
42
- company_name = company_name.strip().upper()
43
-
44
- # Calculate dates for last 6 months
45
- end_date = datetime.now()
46
- start_date = end_date - timedelta(days=180) # Approximately 6 months
47
-
48
- # Setup session with retries for better reliability
49
- session = setup_session_with_retries()
50
-
51
- # Get the data with custom session
52
- ticker = yf.Ticker(company_name, session=session)
53
-
54
- # Add a small delay to be respectful to the API
55
- time.sleep(0.1)
56
-
57
- # Fetch historical data
58
- hist = ticker.history(
59
- start=start_date.strftime("%Y-%m-%d"),
60
- end=end_date.strftime("%Y-%m-%d"),
61
- auto_adjust=True,
62
- prepost=True,
63
- threads=True
64
- )
65
-
66
- if hist.empty:
67
- return f"Error: No data found for ticker symbol: {company_name}. Please verify the ticker symbol is correct."
68
-
69
- # Validate that we have sufficient data
70
- if len(hist) < 10:
71
- return f"Error: Insufficient data found for {company_name}. Only {len(hist)} days of data available."
72
-
73
- # Clean the data - remove any NaN values and ensure proper formatting
74
- hist = hist.dropna()
75
-
76
- if hist.empty:
77
- return f"Error: No valid data remaining for {company_name} after cleaning."
78
-
79
- # Convert to JSON and return
80
- json_data = hist.to_json(date_format='iso', orient='index')
81
-
82
- # Validate JSON was created successfully
83
- try:
84
- json.loads(json_data) # Test if it's valid JSON
85
- except json.JSONDecodeError:
86
- return f"Error: Failed to convert data to JSON format for {company_name}"
87
-
88
- return json_data
89
-
90
- except requests.exceptions.RequestException as e:
91
- return f"Error: Network issue while retrieving data for {company_name}: {str(e)}"
92
- except yf.exceptions.YFinanceException as e:
93
- return f"Error: Yahoo Finance API issue for {company_name}: {str(e)}"
94
- except Exception as e:
95
- return f"Error: Unexpected error retrieving data for {company_name}: {str(e)}"
96
-
97
- def save_financial_data(company_name: str, data: str) -> bool:
98
- """
99
- Save financial data to a JSON file with error handling
100
-
101
- Args:
102
- company_name: str -> the ticker symbol
103
- data: str -> JSON string to save
104
-
105
- Returns:
106
- bool: True if successful, False otherwise
107
- """
108
- try:
109
- filename = f"{company_name}_financial_data.json"
110
-
111
- # Check if data is an error message
112
- if data.startswith("Error:"):
113
- print(f"❌ Data retrieval failed: {data}")
114
- return False
115
-
116
- # Validate JSON before saving
117
- try:
118
- json.loads(data)
119
- except json.JSONDecodeError:
120
- print(f"❌ Invalid JSON data for {company_name}")
121
- return False
122
-
123
- # Ensure directory exists (important for cloud environments)
124
- os.makedirs(os.path.dirname(filename) if os.path.dirname(filename) else '.', exist_ok=True)
125
-
126
- # Save to file
127
- with open(filename, "w", encoding='utf-8') as file:
128
- json.dump(data, file, ensure_ascii=False, indent=2)
129
-
130
- # Verify file was created and has content
131
- if os.path.exists(filename) and os.path.getsize(filename) > 0:
132
- print(f"✅ Successfully saved data for {company_name} to {filename}")
133
- return True
134
- else:
135
- print(f"❌ Failed to save data for {company_name} - file not created or empty")
136
- return False
137
-
138
- except PermissionError:
139
- print(f"❌ Permission denied: Cannot write to file for {company_name}")
140
- return False
141
- except OSError as e:
142
- print(f"❌ OS Error saving data for {company_name}: {str(e)}")
143
- return False
144
- except Exception as e:
145
- print(f"❌ Unexpected error saving data for {company_name}: {str(e)}")
146
- return False
147
-
148
- def validate_ticker_symbol(symbol: str) -> tuple[bool, str]:
149
- """
150
- Basic validation of ticker symbol format
151
-
152
- Args:
153
- symbol: str -> ticker symbol to validate
154
-
155
- Returns:
156
- tuple: (is_valid, message)
157
- """
158
- if not symbol or not symbol.strip():
159
- return False, "Ticker symbol cannot be empty"
160
-
161
- symbol = symbol.strip().upper()
162
-
163
- # Basic format validation
164
- if len(symbol) < 1 or len(symbol) > 10:
165
- return False, "Ticker symbol must be 1-10 characters long"
166
-
167
- if not symbol.isalnum():
168
- return False, "Ticker symbol must contain only letters and numbers"
169
-
170
- return True, "Valid ticker symbol"
171
-
172
- if __name__ == "__main__":
173
- try:
174
- # Check command line arguments
175
- if len(sys.argv) != 2:
176
- print("❌ Usage: python chart.py <TICKER_SYMBOL>")
177
- print("Example: python chart.py AAPL")
178
- sys.exit(1)
179
-
180
- symbol = sys.argv[1].strip().upper()
181
-
182
- # Validate ticker symbol
183
- is_valid, validation_message = validate_ticker_symbol(symbol)
184
- if not is_valid:
185
- print(f"❌ Invalid ticker symbol: {validation_message}")
186
- sys.exit(1)
187
-
188
- print(f"📊 Retrieving financial data for {symbol}...")
189
-
190
- # Retrieve financial data
191
- financial_data = retrieve_financial_data(symbol)
192
-
193
- # Save the data
194
- success = save_financial_data(symbol, financial_data)
195
-
196
- if success:
197
- print(f"🎯 Operation completed successfully for {symbol}")
198
- sys.exit(0)
199
- else:
200
- print(f"❌ Failed to complete operation for {symbol}")
201
- sys.exit(1)
202
-
203
- except KeyboardInterrupt:
204
- print("\n❌ Operation cancelled by user")
205
- sys.exit(1)
206
- except Exception as e:
207
- print(f"❌ Unexpected error: {e}")
208
- sys.exit(1)