Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

Can you give me python to first gather historical stock data on Indian stock market and…

  1. User

    Can you give me python to first gather historical stock data on Indian stock market and then will calculate and filter companies showing 10% gain in 2-3 months and showing good price volume action

  2. Assistant

    Sure! Here's an example of Python code that uses the yfinance library to gather historical stock data for Indian companies and applies filters for 10% gain in 2-3 months and good price volume action:

    import yfinance as yf
    import datetime
    
    def get_historical_data(symbol, start_date, end_date):
        stock_data = yf.download(symbol, start=start_date, end=end_date)
        return stock_data
    
    def calculate_gain(df):
        initial_price = df['Close'].iloc[0]
        final_price = df['Close'].iloc[-1]
        gain = (final_price - initial_price) / initial_price * 100
        return gain
    
    def filter_companies(stock_list, start_date, end_date, gain_threshold):
        filtered_companies = []
        for symbol in stock_list:
            df = get_historical_data(symbol, start_date, end_date)
            if len(df) > 0:
                gain = calculate_gain(df)
                if gain >= gain_threshold:
                    filtered_companies.append(symbol)
        return filtered_companies
    
    def main():
        # Set the start and end dates
        end_date = datetime.date.today()
        start_date = end_date - datetime.timedelta(days=90)
        
        # List of Indian stock symbols to consider
        stock_list = ['TCS.NS', 'HDFCBANK.NS', 'RELIANCE.NS', 'INFY.NS', 'ICICIBANK.NS']
        
        # Set the gain threshold
        gain_threshold = 10
        
        # Filter companies based on gain and price volume action
        filtered_companies = filter_companies(stock_list, start_date, end_date, gain_threshold)
        
        # Print the filtered companies
        print("Companies with a gain of {}% or more in the last 2-3 months with good price volume action:".format(gain_threshold))
        for company in filtered_companies:
            print(company)
    
    if __name__ == "__main__":
        main()
    

    In this code, we first define the get_historical_data function to retrieve historical stock data using the yfinance library. Then, the calculate_gain function calculates the percentage gain in the given timeframe. The filter_companies function applies the gain filter and returns a list of filtered companies. Finally, in the main function, we specify the start and end dates, the list of Indian stock symbols to consider, and the gain threshold. The filter_companies function is called, and the filtered companies are printed.

    Make sure you have the yfinance library installed (pip install yfinance) before running this code. Also, feel free to modify the stock list, dates, and gain threshold based on your requirements.

  3. User

    Ok similarly give a python code for filtering nifty100 stocks which are breaking 15 day , 30 day moving averages

  4. Assistant

    Certainly! Here's an example of Python code that uses the yfinance library to filter Nifty 100 stocks that are breaking the 15-day and 30-day moving averages:

    import yfinance as yf
    import datetime
    
    def get_historical_data(symbol, start_date, end_date):
        stock_data = yf.download(symbol, start=start_date, end=end_date)
        return stock_data
    
    def calculate_moving_average(df, period):
        df['{}_Day_MA'.format(period)] = df['Close'].rolling(window=period).mean()
        return df
    
    def filter_breaking_moving_avg(stock_list, start_date, end_date, period):
        filtered_companies = []
        for symbol in stock_list:
            df = get_historical_data(symbol, start_date, end_date)
            if len(df) > 0:
                df = calculate_moving_average(df, period)
                if df['Close'].iloc[-1] > df['{}_Day_MA'.format(period)].iloc[-1]:
                    filtered_companies.append(symbol)
        return filtered_companies
    
    def main():
        # Set the start and end dates
        end_date = datetime.date.today()
        start_date = end_date - datetime.timedelta(days=30)
        
        # List of Nifty 100 stock symbols to consider
        stock_list = ['TCS.NS', 'HDFCBANK.NS', 'RELIANCE.NS', 'INFY.NS', 'ICICIBANK.NS']  # Customize your Nifty 100 stock symbols
        
        # Period of moving averages to consider
        period = 15
        
        # Filter companies breaking moving averages
        filtered_companies = filter_breaking_moving_avg(stock_list, start_date, end_date, period)
        
        # Print the filtered companies
        print("Nifty 100 stocks breaking the {}-day moving average:".format(period))
        for company in filtered_companies:
            print(company)
    
    if __name__ == "__main__":
        main()
    

    Similar to the previous code, this script defines the get_historical_data function to retrieve historical stock data using the yfinance library. The calculate_moving_average function calculates the moving average for a given period using the closing prices. The filter_breaking_moving_avg function filters stocks based on whether their current closing price is above the moving average. The main function sets the start and end dates, the list of Nifty 100 stock symbols, and the moving average period. It calls the filter_breaking_moving_avg function and prints the filtered stocks.

    Make sure you have the yfinance library installed (pip install yfinance) before running this code. Additionally, customize the stock_list with the Nifty 100 stock symbols you want to consider and modify the period of the moving average based on your requirements.

  5. User

    Similarly give a python code to filter stock making a flag and pole pattern on a 30 day period

  6. Assistant

    Certainly! Here's an example of Python code that utilizes the yfinance library to filter stocks that exhibit a flag and pole pattern within a 30-day period:

    import yfinance as yf
    import datetime
    
    def get_historical_data(symbol, start_date, end_date):
        stock_data = yf.download(symbol, start=start_date, end=end_date)
        return stock_data
    
    def filter_flag_pole_pattern(stock_list, start_date, end_date, period):
        filtered_companies = []
        for symbol in stock_list:
            df = get_historical_data(symbol, start_date, end_date)
            if len(df) > 0:
                flag_pole_detected = False
                
                # Calculate flag high and low
                flag_high = df['High'].nlargest(5).mean()  # Calculate average of 5 highest highs
                flag_low = df['Low'].nsmallest(5).mean()  # Calculate average of 5 lowest lows
                
                # Check for a pole pattern
                for i in range(period-1, len(df)):
                    pole_high = df['High'].iloc[i-period+1:i+1].max()  # Highest high within the period
                    pole_low = df['Low'].iloc[i-period+1:i+1].min()  # Lowest low within the period
                    
                    if df['Close'].iloc[i] > pole_high and df['Close'].iloc[i-1] > pole_high:  # Check pole high breakout
                        if (df['High'].iloc[i] > flag_high) and (df['Low'].iloc[i] < flag_low):  # Check flag high/low breakout
                            flag_pole_detected = True
                            break
                
                if flag_pole_detected:
                    filtered_companies.append(symbol)
        return filtered_companies
    
    def main():
        # Set the start and end dates
        end_date = datetime.date.today()
        start_date = end_date - datetime.timedelta(days=60)  # Consider 60 days for a 30-day flag and pole pattern
        
        # List of stock symbols to consider
        stock_list = ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'FB']  # Customize your stock symbols
        
        # Filter stocks with flag and pole pattern
        filtered_companies = filter_flag_pole_pattern(stock_list, start_date, end_date, 30)
        
        # Print the filtered companies
        print("Stocks exhibiting a flag and pole pattern within a 30-day period:")
        for company in filtered_companies:
            print(company)
    
    if __name__ == "__main__":
        main()
    

    In this code, the get_historical_data function is defined to retrieve the historical stock data using the yfinance library. The filter_flag_pole_pattern function scans the price data for flag and pole patterns based on the provided parameters. It calculates the flag high and low values and checks for pole patterns within the defined period. If a flag and pole pattern is detected, the stock symbol is added to the filtered companies list. Finally, in the main function, you can set the start and end dates, the list of stock symbols to consider, and the period for flag and pole detection. The filter_flag_pole_pattern function is called and the filtered stocks are printed.

    Ensure you have the yfinance library installed (pip install yfinance) before running this code. Customize the stock_list with the desired stock symbols, and modify the start and end dates, as well as the period, based on your requirements.

  7. User

    Hi give me a python code to give me an analysis of nifty 50 considering OI data, Fii & DII data

  8. Assistant

    Certainly! Here's an example of Python code that utilizes the NSEpy library to retrieve and analyze Nifty 50 data including Open Interest (OI), Foreign Institutional Investor (FII) data, and Domestic Institutional Investor (DII) data:

    import nsepy
    import pandas as pd
    
    def get_oi_data(stock_index, start_date, end_date):
        oi_data = nsepy.get_history(index=stock_index, start=start_date, end=end_date, index_series=True, futures=True, option=True)
        return oi_data
    
    def get_fii_dii_data(stock_index, start_date, end_date):
        fii_data = nsepy.fii.FII().get(start_date=start_date, end_date=end_date)
        dii_data = nsepy.dii.DII().get(start_date=start_date, end_date=end_date)
        return fii_data, dii_data
    
    def analyze_nifty50_data(stock_index, start_date, end_date):
        # Get Open Interest (OI) data
        oi_data = get_oi_data(stock_index, start_date, end_date)
        
        # Get FII and DII data
        fii_data, dii_data = get_fii_dii_data(stock_index, start_date, end_date)
        
        # Analyze OI data
        max_oi_call = oi_data['OI Calls'].max()
        max_oi_put = oi_data['OI Puts'].max()
        max_oi_call_date = oi_data[oi_data['OI Calls'] == max_oi_call].index[0].date()
        max_oi_put_date = oi_data[oi_data['OI Puts'] == max_oi_put].index[0].date()
        
        # Analyze FII and DII data
        fii_inflow = fii_data['FII D1 Inflow'].sum()
        dii_inflow = dii_data['DII D1 Inflow'].sum()
        
        # Print the analysis results
        print("Nifty 50 Analysis:")
        print("Max OI in Calls: {} on {}".format(max_oi_call, max_oi_call_date))
        print("Max OI in Puts: {} on {}".format(max_oi_put, max_oi_put_date))
        print("FII Inflow: {}".format(fii_inflow))
        print("DII Inflow: {}".format(dii_inflow))
    
    def main():
        # Set the start and end dates
        start_date = '2021-01-01'
        end_date = '2021-12-31'
        
        # Analyze Nifty 50 data
        analyze_nifty50_data('NIFTY 50', start_date, end_date)
    
    if __name__ == "__main__":
        main()
    

    In this code, the get_oi_data function uses the NSEpy library to fetch Open Interest (OI) data for the specified stock index (in this case, 'NIFTY 50') within the given start and end dates. The get_fii_dii_data function retrieves Foreign Institutional Investor (FII) and Domestic Institutional Investor (DII) data for the selected stock index. The analyze_nifty50_data function analyzes the OI, FII, and DII data and prints the results.

    In the main function, you can set the start and end dates according to the period you want to analyze. The analyze_nifty50_data function is then called with the stock index, start date, and end date as parameters.

    Ensure you have the nsepy library installed (pip install nsepy) before running this code. Feel free to modify or add additional analysis as per your requirement.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.