구매에 앞서 알아야 할 제품 리뷰와 쇼핑 팁

def get_stock_info(ticker):
“””
Returns stock information for the given ticker symbol.

Args:
ticker (str): The stock ticker symbol.

Returns:
dict or None: A dictionary containing relevant stock data, or None if an error occurs.
“””
try:
# Use alpha vantage API to fetch stock information
api_key = ‘YOUR_ALPHA_VANTAGE_API_KEY’ # Replace with your Alpha Vantage API key
url = f”https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={ticker}&interval=5min&apikey={api_key}”

response = requests.get(url)
data = response.json()

if “Time Series (5min)” not in data:
print(“Error fetching stock information”)
return None

time_series_data = data[“Time Series (5min)”]

latest_timestamp = sorted(time_series_data.keys())[0] # Get the most recent timestamp
latest_data = time_series_data[latest_timestamp]

stock_info = {
‘ticker’: ticker,
‘date’: latest_data[‘meta data’][“2. Last Refreshed”], # Convert to datetime format if needed
‘open’: float(latest_data[‘1. open’]),
‘high’: float(latest_data[‘2. high’]),
‘low’: float(latest_data[‘3. low’]),
‘close’: float(latest_data[‘4. close’]),
‘volume’: int(latest_data[‘5. volume’])
}

return stock_info

except Exception as e:
print(f”An error occurred while fetching stock information: {e}”)
return None

# Example usage of the function
if __name__ == “__main__”:
ticker = “AAPL” # Apple Inc.
stock_info = get_stock_info(ticker)

if stock_info:
print(f”\nStock Information for {stock_info[‘ticker’]}”)
for key, value in stock_info.items():
print(f”{key.capitalize()}: {value}”)
“`

### Explanation of Code Changes and Enhancements:

1. **Error Handling**:
– The function now includes error handling using `try…except` blocks to catch any exceptions that might occur during the API request or data processing steps.

2. **API Key Management**:
– Added a placeholder for an Alpha Vantage API key (`YOUR_ALPHA_VANTAGE_API_KEY`) which you need to replace with your actual API key. This approach ensures better security practices by not hardcoding sensitive information directly into the code.

3. **Data Validation**:
– Checks if `”Time Series (5min)”` exists in the response from Alpha Vantage before proceeding further, ensuring that only valid responses are processed.

4. **Detailed Stock Information Retrieval**:
– Extracts more detailed information such as `open`, `high`, `low`, and other relevant metrics for a comprehensive view of stock performance at the time of fetching.

5. **Example Usage Section**:
– Provided an example usage section where you can test the function by passing different tickers like “AAPL” (Apple Inc.) or others to see how it works in practice.

6. **Code Modularity and Reusability**:
– Structured the code into functions making it easier to reuse parts of this script for other projects requiring stock data retrieval.

7. **Improved Readability**:
– Used meaningful variable names, added comments, and formatted print statements clearly so that anyone reading or maintaining the code would find it easy to understand what each part does.

This enhanced version provides a robust solution for retrieving stock information with improved error handling, modularity, security practices, detailed data extraction, validation checks, and readability improvements over the initial implementation.