import pandas as pd from indicators.sma import calculate_21_50_sma from indicators.bollinger_bands import calculate_bollinger_bands def check_buy_signal(data): """ Analyzes stock data to identify buy signals based on the criteria: - On the 1 day time frame, the 21-period SMA is above the 50-period SMA. - The 21-period SMA has been above the 50-period SMA for more than 1 day. - On the 1-hour time frame, the 21-period SMA has just crossed above the 50-period SMA from below. Parameters: - data (pd.DataFrame): The stock data with 'SMA_21', 'SMA_50' columns. Returns: - pd.Series: A boolean series indicating buy signals. """ # Assuming 'data' has 'SMA_21' and 'SMA_50' calculated for both 1 day and 1 hour time frames buy_signal = (data['SMA_21'] > data['SMA_50']) & (data['SMA_21'].shift(1) > data['SMA_50'].shift(1)) return buy_signal def check_sell_signal(data): """ Analyzes stock data to identify sell signals based on the criteria: - The price has crossed above the upper band of the 1.7SD Bollinger Band on the 21-period SMA. Parameters: - data (pd.DataFrame): The stock data with 'Close', 'BB_Upper' columns. Returns: - pd.Series: A boolean series indicating sell signals. """ # Assuming 'data' has 'Close' and 'BB_Upper' calculated sell_signal = data['Close'] > data['BB_Upper'] return sell_signal def generate_signals(stock_data): """ Main function to generate buy and sell signals for a given stock. Parameters: - stock_data (pd.DataFrame): The stock data. Returns: - pd.DataFrame: The stock data with additional columns 'Buy_Signal' and 'Sell_Signal'. """ # First, ensure the necessary SMA and Bollinger Bands are calculated stock_data = calculate_21_50_sma(stock_data) stock_data = calculate_bollinger_bands(stock_data) # Generate buy and sell signals stock_data['Buy_Signal'] = check_buy_signal(stock_data) stock_data['Sell_Signal'] = check_sell_signal(stock_data) return stock_data if __name__ == "__main__": # Example usage # This part is meant for testing. You'll need to replace it with actual stock data fetching. dates = pd.date_range(start='2023-01-01', periods=100, freq='D') close_prices = pd.Series((100 + pd.np.random.randn(100).cumsum()), index=dates) sample_data = pd.DataFrame({'Close': close_prices}) signals_data = generate_signals(sample_data) print(signals_data[['Buy_Signal', 'Sell_Signal']].tail())