Skip to content

Instantly share code, notes, and snippets.

@win3zz
Last active June 17, 2024 06:02
Show Gist options
  • Save win3zz/4df5562ef1c205f7818e87ae7a4e9cc8 to your computer and use it in GitHub Desktop.
Save win3zz/4df5562ef1c205f7818e87ae7a4e9cc8 to your computer and use it in GitHub Desktop.
Compare Stock Performance Over Multiple Time Frames with Yahoo Finance API and Matplotlib

Compare Stock Performance Over Multiple Time Frames with Yahoo Finance API and Matplotlib

How to Use

Compare the performance of a stock across two or more time frames using the Yahoo Finance API and the Matplotlib Python library. Adjust the stock symbol and time frames according to your requirements and save the content in a file named script.py.

import requests
import matplotlib.pyplot as plt
from datetime import datetime

proxy = {'http': 'http://127.0.0.1:8080','https': 'https://127.0.0.1:8080'}

def fetch_stock_data(symbol, period1, period2, interval):
    url = f'http://query1.finance.yahoo.com/v8/finance/chart/{symbol}?period1={period1}&period2={period2}&interval={interval}&includePrePost=true&events=div%7Csplit%7Cearn&useYfid=true&lang=en-US&region=US'
    headers = {
        'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:125.0) Gecko/20100101 Firefox/125.0'
    }
    response = requests.get(url, headers=headers) #, proxies=proxy)
    try:
        data = response.json()
    except Exception as e:
        print("Error fetching data:", e)
        print("Response content:", response.content)
        return None
    return data

def generate_comparison_graph(data_list, timeframe_list):
    plt.figure(figsize=(12, 6))

    for i, data in enumerate(data_list):
        timestamps = data['chart']['result'][0]['timestamp']
        prices = data['chart']['result'][0]['indicators']['quote'][0]['close']
        # plt.plot(timestamps, prices, label=f'BSE SENSEX ({timeframe_list[i]})')
        plt.plot(prices, label=f'BSE SENSEX ({timeframe_list[i]})')

    #plt.xlabel('Date')
    plt.ylabel('Price')
    plt.title('BSE SENSEX Prices Comparison')
    plt.legend()
    plt.show()

def main():
    symbol = '^BSESN'

    # Define the timeframes
    timeframes = [
        ('1999-10-06', '2004-05-12'),
        ('2004-05-13', '2009-05-15'),
        ('2009-05-16', '2014-05-15'),
        ('2014-05-16', '2019-05-22'),
        ('2019-05-23', '2024-04-29')
    ]
    interval = '1d'  # Daily interval

    # Convert timeframes to Unix timestamps and fetch data
    data_list = []
    timeframe_list = []
    for start_date, end_date in timeframes:
        period1 = int(datetime.strptime(start_date, '%Y-%m-%d').timestamp())
        period2 = int(datetime.strptime(end_date, '%Y-%m-%d').timestamp())
        data = fetch_stock_data(symbol, period1, period2, interval)
        data_list.append(data)
        timeframe_list.append(f"{start_date} to {end_date}")

    # Generate comparison graph
    generate_comparison_graph(data_list, timeframe_list)

if __name__ == "__main__":
    main()

Execute the script using the python3 script.py command:

bipin@bipin-VirtualBox:~$ python3 script.py

Upon successful execution, the script will display the graph as shown below. Please note, pictures of politicians are not included; those are added by me. ;)

Figure_1

Data:

Here's the dates I used:

Election Dates Result Declaration Dates Oath Date PM Name - Party in Power Tenure Majority Seats
5 Sep - 3 Oct 1999 6 Oct 1999 13 Oct 1999 Atal Bihari Vajpayee - BJP (NDA) 13 Oct 1999 - 22 May 2004 182
20 Apr - 10 May 2004 13 May 2004 22 May 2004 Manmohan Singh - INC (UPA) 22 May 2004 - 26 May 2014 145
16 Apr - 13 May 2009 16 May 2009 22 May 2009 Manmohan Singh - INC (UPA) 22 May 2009 - 26 May 2014 206
7 Apr - 12 May 2014 16 May 2014 26 May 2014 Narendra Modi - BJP (NDA) 26 May 2014 - Present 282
11 Apr - 19 May 2019 23 May 2019 30 May 2019 Narendra Modi - BJP (NDA) 30 May 2019 - Present 303
19 Apr - 1 June 2024 4 June 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment