Python Stock Data Download by Coder Singh | Sep 2024

SeniorTechInfo
2 Min Read

The Easy Way to Fetch Stock Data with Python

Python Stock Data Download by Coder Singh | Sep 2024

Are you looking to fetch stock data for specific start and end dates? Look no further! With Python and the yfinance library, it’s easier than ever.

                
                    import yfinance as yf
                    # Specify stock symbol and dates
                    stock_symbol = 'AAPL'
                    start_date = '2023-01-01'
                    end_date = '2023-09-01'
                    # Download stock data for specific dates
                    stock_data = yf.download(stock_symbol, start=start_date, end=end_date)
                    # Display the first few rows of the data
                    print(stock_data.head())
                
            

By running this code snippet, you can retrieve Apple’s stock data from January 1, 2023, to September 1, 2023.

If you prefer to fetch data for a relative period, like the last year, you can use the yf.Ticker method with the period parameter.

                
                    import yfinance as yf
                    # Define the stock symbol
                    stock_symbol = 'AAPL'
                    # Get stock data for the last 1 year
                    stock = yf.Ticker(stock_symbol)
                    stock_data = stock.history(period='1y')  # '1y' means one year
                    # Display the first few rows of the data
                    print(stock_data.head())
                
            

The period argument in the history() method allows you to specify relative time frames like 1 day, 5 days, 1 month, 6 months, 1 year, 5 years, or all available data.

If you need to specify a custom period, such as the last 30 days, you can easily do so using Python’s datetime module:

                
                    import yfinance as yf
                    from datetime import datetime, timedelta
                    # Define the stock symbol
                    stock_symbol = 'AAPL'
                    # Get today's date and calculate the date 30 days ago
                    end_date = datetime.now()
                    start_date = end_date - timedelta(days=30)
                    # Download stock data for the last 30 days
                    stock_data = yf.download(stock_symbol, start=start_date, end=end_date)
                    # Display the first few rows of the data
                    print(stock_data.head())
                
            

With these simple Python scripts, you can easily fetch stock data for specific dates or relative periods, making it convenient to analyze and track stock performance.

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *