Sure! Below is a comprehensive Google Colab Python script that:
- Fetches Stock Data: Retrieves stock data from NSE and BSE, including large-cap, mid-cap, and small-cap stocks using the
yfinance library.
- Performs Analysis: Utilizes technical indicators (such as Moving Averages and Relative Strength Index) to determine buy/sell signals.
- Provides Recommendations: Suggests which stocks are good for investment along with recommended buy/sell actions and quantities.
- Optimizes Performance: Implements efficient data handling to ensure the code runs reasonably fast.
Prerequisites
Before running the script, ensure you have the necessary Python libraries installed. The script includes installation commands, but you can also install them manually.
Step-by-Step Implementation
- Setup and Installation
- Define Stock Tickers
- Fetch Stock Data
- Perform Technical Analysis
- Generate Buy/Sell Recommendations
- Display Results
Let's dive into each step.
1. Setup and Installation
First, we'll install the required libraries:
yfinance: To fetch stock data.
pandas_ta: For technical analysis indicators.
nsetools: To fetch NSE stock tickers (optional but recommended for dynamic ticker retrieval).
# Install necessary libraries
!pip install yfinance pandas_ta nsetools
import yfinance as yf
import pandas as pd
import pandas_ta as ta
from nsetools import Nse
import datetime
import warnings
warnings.filterwarnings('ignore')
2. Define Stock Tickers
For demonstration purposes, we'll define a list of popular NSE and BSE tickers across large-cap, mid-cap, and small-cap segments. In a production environment, you might want to dynamically fetch these tickers.
# Sample list of tickers for demonstration
# You can expand this list or fetch dynamically using nsetools or other APIs
stock_tickers = [
# Large-cap
'RELIANCE.NS', 'TCS.NS', 'HDFCBANK.NS', 'INFY.NS',
# Mid-cap
'ADANIPORTS.NS', 'BAJAJ-AUTO.NS', 'CIPLA.NS',
# Small-cap
'ABB.NS', 'MANAPPURAM.NS', 'TECHM.NS'
]
Note: Tickers should be suffixed with .NS for NSE and .BO for BSE if needed. Ensure the tickers are accurate to avoid errors during data fetching.
3. Fetch Stock Data
We'll fetch historical data for each ticker using yfinance. To optimize performance, we'll limit the historical period (e.g., last 1 year) and use multi-threading where possible.
# Define the time period for historical data
end_date = datetime.datetime.today()
start_date = end_date - datetime.timedelta(days=365) # Last 1 year
# Function to fetch data
def fetch_data(ticker):
try:
stock = yf.Ticker(ticker)
df = stock.history(start=start_date, end=end_date)
if df.empty:
print(f"No data found for {ticker}")
return None
df.reset_index(inplace=True)
df['Ticker'] = ticker
return df
except Exception as e:
print(f"Error fetching data for {ticker}: {e}")
return None
# Fetch data for all tickers
import concurrent.futures
all_data = []
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
futures = {executor.submit(fetch_data, ticker): ticker for ticker in stock_tickers}
for future in concurrent.futures.as_completed(futures):
data = future.result()
if data is not None:
all_data.append(data)
# Combine all data into a single DataFrame
combined_df = pd.concat(all_data, ignore_index=True)
print("Data fetching completed.")
4. Perform Technical Analysis
We'll use technical indicators to analyze the stock performance:
- Moving Averages (MA): 50-day and 200-day moving averages to identify trends.
- Relative Strength Index (RSI): To identify overbought or oversold conditions.
# Initialize empty list to store analysis results
analysis_results = []
# Get list of unique tickers
unique_tickers = combined_df['Ticker'].unique()
for ticker in unique_tickers:
df = combined_df[combined_df['Ticker'] == ticker].copy()
df.set_index('Date', inplace=True)
# Calculate Moving Averages
df['MA50'] = df['Close'].rolling(window=50).mean()
df['MA200'] = df['Close'].rolling(window=200).mean()
# Calculate RSI
df['RSI'] = ta.rsi(df['Close'], length=14)
# Latest data point
latest = df.iloc[-1]
# Buy Signal: MA50 > MA200 and RSI < 30 (Oversold)
if latest['MA50'] > latest['MA200'] and latest['RSI'] < 30:
signal = 'Buy'
# Sell Signal: MA50 < MA200 and RSI > 70 (Overbought)
elif latest['MA50'] < latest['MA200'] and latest['RSI'] > 70:
signal = 'Sell'
else:
signal = 'Hold'
analysis_results.append({
'Ticker': ticker,
'Close_Price': latest['Close'],
'MA50': latest['MA50'],
'MA200': latest['MA200'],
'RSI': latest['RSI'],
'Signal': signal
})
# Create a DataFrame from the analysis results
analysis_df = pd.DataFrame(analysis_results)
5. Generate Buy/Sell Recommendations
Based on the signals generated, we'll recommend action and suggest quantities. For simplicity, we'll assume a fixed investment amount per stock. In a real-world scenario, you'd consider portfolio size, risk tolerance, stock price, and other financial metrics.
# Define a fixed investment amount (e.g., ₹10,000 per Buy signal)
investment_amount = 10000 # in INR
# Function to calculate quantity to buy
def calculate_quantity(price, amount):
return int(amount / price)
# Apply recommendations
analysis_df['Recommended_Action'] = analysis_df['Signal']
analysis_df['Recommended_Quantity'] = analysis_df.apply(
lambda row: calculate_quantity(row['Close_Price'], investment_amount) if row['Signal'] == 'Buy' else
calculate_quantity(row['Close_Price'], investment_amount) if row['Signal'] == 'Sell' else 0,
axis=1
)
# Display analysis and recommendations
buy_recommendations = analysis_df[analysis_df['Signal'] == 'Buy']
sell_recommendations = analysis_df[analysis_df['Signal'] == 'Sell']
print("\nBuy Recommendations:")
print(buy_recommendations[['Ticker', 'Close_Price', 'RSI', 'Recommended_Action', 'Recommended_Quantity']])
print("\nSell Recommendations:")
print(sell_recommendations[['Ticker', 'Close_Price', 'RSI', 'Recommended_Action', 'Recommended_Quantity']])
6. Full Google Colab Script
Below is the complete script combined. You can copy and paste it into a Google Colab notebook and execute each cell sequentially.
# Install necessary libraries
!pip install yfinance pandas_ta nsetools
import yfinance as yf
import pandas as pd
import pandas_ta as ta
from nsetools import Nse
import datetime
import warnings
warnings.filterwarnings('ignore')
import concurrent.futures
# Define the time period for historical data
end_date = datetime.datetime.today()
start_date = end_date - datetime.timedelta(days=365) # Last 1 year
# Sample list of tickers for demonstration
# You can expand this list or fetch dynamically using nsetools or other APIs
stock_tickers = [
# Large-cap
'RELIANCE.NS', 'TCS.NS', 'HDFCBANK.NS', 'INFY.NS',
# Mid-cap
'ADANIPORTS.NS', 'BAJAJ-AUTO.NS', 'CIPLA.NS',
# Small-cap
'ABB.NS', 'MANAPPURAM.NS', 'TECHM.NS'
]
# Function to fetch data
def fetch_data(ticker):
try:
stock = yf.Ticker(ticker)
df = stock.history(start=start_date, end=end_date)
if df.empty:
print(f"No data found for {ticker}")
return None
df.reset_index(inplace=True)
df['Ticker'] = ticker
return df
except Exception as e:
print(f"Error fetching data for {ticker}: {e}")
return None
# Fetch data for all tickers
all_data = []
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
futures = {executor.submit(fetch_data, ticker): ticker for ticker in stock_tickers}
for future in concurrent.futures.as_completed(futures):
data = future.result()
if data is not None:
all_data.append(data)
# Combine all data into a single DataFrame
combined_df = pd.concat(all_data, ignore_index=True)
print("Data fetching completed.")
# Initialize empty list to store analysis results
analysis_results = []
# Get list of unique tickers
unique_tickers = combined_df['Ticker'].unique()
for ticker in unique_tickers:
df = combined_df[combined_df['Ticker'] == ticker].copy()
df.set_index('Date', inplace=True)
# Calculate Moving Averages
df['MA50'] = df['Close'].rolling(window=50).mean()
df['MA200'] = df['Close'].rolling(window=200).mean()
# Calculate RSI
df['RSI'] = ta.rsi(df['Close'], length=14)
# Latest data point
latest = df.iloc[-1]
# Buy Signal: MA50 > MA200 and RSI < 30 (Oversold)
if latest['MA50'] > latest['MA200'] and latest['RSI'] < 30:
signal = 'Buy'
# Sell Signal: MA50 < MA200 and RSI > 70 (Overbought)
elif latest['MA50'] < latest['MA200'] and latest['RSI'] > 70:
signal = 'Sell'
else:
signal = 'Hold'
analysis_results.append({
'Ticker': ticker,
'Close_Price': latest['Close'],
'MA50': latest['MA50'],
'MA200': latest['MA200'],
'RSI': latest['RSI'],
'Signal': signal
})
# Create a DataFrame from the analysis results
analysis_df = pd.DataFrame(analysis_results)
# Define a fixed investment amount (e.g., ₹10,000 per Buy signal)
investment_amount = 10000 # in INR
# Function to calculate quantity to buy
def calculate_quantity(price, amount):
return int(amount / price)
# Apply recommendations
analysis_df['Recommended_Action'] = analysis_df['Signal']
analysis_df['Recommended_Quantity'] = analysis_df.apply(
lambda row: calculate_quantity(row['Close_Price'], investment_amount) if row['Signal'] == 'Buy' else
calculate_quantity(row['Close_Price'], investment_amount) if row['Signal'] == 'Sell' else 0,
axis=1
)
# Display analysis and recommendations
buy_recommendations = analysis_df[analysis_df['Signal'] == 'Buy']
sell_recommendations = analysis_df[analysis_df['Signal'] == 'Sell']
print("\nBuy Recommendations:")
print(buy_recommendations[['Ticker', 'Close_Price', 'RSI', 'Recommended_Action', 'Recommended_Quantity']])
print("\nSell Recommendations:")
print(sell_recommendations[['Ticker', 'Close_Price', 'RSI', 'Recommended_Action', 'Recommended_Quantity']])
Explanation of the Analysis
-
Moving Averages (MA50 & MA200):
- MA50 > MA200: Indicates an uptrend. When combined with a low RSI, it suggests a potential buying opportunity.
- MA50 < MA200: Indicates a downtrend. When combined with a high RSI, it suggests a potential selling opportunity.
-
Relative Strength Index (RSI):
- RSI < 30: The stock is potentially oversold, indicating a buying opportunity.
- RSI > 70: The stock is potentially overbought, indicating a selling opportunity.
-
Buy/Sell Signals:
- Buy: If the MA50 is above MA200 and RSI is below 30.
- Sell: If the MA50 is below MA200 and RSI is above 70.
- Hold: No clear signal to buy or sell.
-
Recommended Quantity:
- Based on a fixed investment amount (e.g., ₹10,000), the script calculates how many shares one should buy or sell. This is a simplistic approach and can be enhanced based on portfolio size, risk management, etc.
Customization and Enhancements
- Dynamic Ticker Retrieval: Use
nsetools or other APIs to fetch real-time lists of large-cap, mid-cap, and small-cap stocks.
- Additional Indicators: Incorporate more technical indicators like MACD, Bollinger Bands, etc., for a more robust analysis.
- Machine Learning Models: Implement predictive models to forecast stock prices or classify buy/sell/hold signals based on historical data.
- Portfolio Optimization: Allocate investment amounts based on diversification strategies, risk assessment, and expected returns.
- Backtesting: Test the strategy against historical data to evaluate its performance before applying it to live data.
Caveats
- Data Accuracy: Ensure that the stock tickers are correct and data fetched is accurate.
- Market Conditions: Technical indicators are based on historical data and may not always predict future movements accurately.
- No Financial Advice: This script is for educational purposes. Consult with a financial advisor before making investment decisions.
Feel free to modify and enhance the script according to your specific requirements and investment strategies. Happy investing!