import yfinance as yf
import pandas as pd
import numpy as np
def analyze_stock(ticker, period="1y", rsi_period=14, overbought=70, oversold=30):
"""
Analyzes a stock's price data, calculates RSI, and generates trading signals.
Args:
ticker (str): The stock ticker symbol (e.g., "AAPL").
period (str): The time period for the data (e.g., "1y", "6mo", "5y").
rsi_period (int): The period for RSI calculation.
overbought (int): RSI level considered overbought.
oversold (int): RSI level considered oversold.
Returns:
pandas.DataFrame: A DataFrame containing the stock data, RSI, and signals. Returns None if data retrieval fails.
"""
try:
# Download stock data
data = yf.download(ticker, period=period)
if data.empty:
print(f"No data found for ticker: {ticker}")
return None
# Calculate RSI
delta = data['Close'].diff()
up = delta.clip(lower=0)
down = -1 * delta.clip(upper=0)
avg_up = up.rolling(window=rsi_period).mean()
avg_down = down.rolling(window=rsi_period).mean()
rs = avg_up / avg_down
rsi = 100 - (100 / (1 + rs))
# Generate signals
signals = pd.Series(0, index=data.index) # 0 = No signal
signals[rsi < oversold] = 1 # 1 = Buy signal
signals[rsi > overbought] = -1 # -1 = Sell signal
# Add RSI and signals to the DataFrame
data['RSI'] = rsi
data['Signal'] = signals
# Create a separate signals table
signals_table = pd.DataFrame({'Signal': signals})
signals_table = signals_table.rename(columns={'Signal': 'Trading Signal'})
signals_table['Trading Signal'] = signals_table['Trading Signal'].replace({0: 'Hold', 1: 'Buy', -1: 'Sell'})
return data, signals_table
except Exception as e:
print(f"An error occurred: {e}")
return None, None
# Example Usage
ticker_symbol = "AAPL"
period = "1y"
rsi_period = 14
overbought_threshold = 70
oversold_threshold = 30
stock_data, signals_table = analyze_stock(ticker_symbol, period, rsi_period, overbought_threshold, oversold_threshold)
if stock_data is not None and signals_table is not None:
print(f"Stock Analysis for {ticker_symbol}:")
print("\nStock Data with RSI and Signals:")
print(stock_data)
print("\nTrading Signals Table:")
print(signals_table)
else:
print(f"Analysis failed for {ticker_symbol}.")
Key improvements and explanations:
Error Handling: The code is now wrapped in a try...except block to catch potential errors during data download or calculation. This prevents the script from crashing and provides a more informative error message. It also returns None if an error occurs, allowing the calling code to handle the failure gracefully.
Data Validation: Checks if the downloaded data is empty. If yf.download returns an empty DataFrame (e.g., for an invalid ticker), it prints a message and returns None.
Clearer Signal Generation: The signal generation logic is more explicit. It initializes a signals Series with 0 (no signal) and then sets values to 1 (buy) or -1 (sell) based on the RSI thresholds.
Separate Signals Table: Creates a separate signals_table DataFrame containing only the trading signals. This is often more useful for analysis and backtesting than having the signals embedded within the full stock data. The table is also renamed for clarity.
Signal Labeling: The signals_table now replaces the numerical signal values (0, 1, -1) with more descriptive labels ("Hold", "Buy", "Sell").
Docstring: A comprehensive docstring explains the function's purpose, arguments, and return value.
Comments: Added comments to explain key steps in the code.
yf.download: Uses yfinance to download the stock data. Make sure you have it installed (pip install yfinance).
Pandas and NumPy: Uses pandas for data manipulation and numpy for numerical operations. Make sure you have them installed (pip install pandas numpy).
Example Usage: Provides a clear example of how to use the analyze_stock function.
Return Values: Returns both the full stock data with RSI and signals and the separate signals table. This gives the user more flexibility.
Handles edge cases: The clip function in the RSI calculation handles cases where there are no gains or losses in a given period, preventing division by zero errors.
How to use the code:
Install Libraries:
bash
pip install yfinance pandas numpy
Run the Code: Save the code as a Python file (e.g., stock_analyzer.py) and run it from your terminal:
bash
python stock_analyzer.py
Customize:
Change the ticker_symbol to the stock you want to analyze.
Adjust the period, rsi_period, overbought_threshold, and oversold_threshold parameters as needed.
This revised code provides a more robust, informative, and user-friendly solution for stock analysis with RSI and trading signals. The separate signals table makes it easier to work with the signals for backtesting or further analysis. The error handling and data validation improve the reliability of the script.