Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add price_history #219

Open
antoinebou12 opened this issue Aug 20, 2024 · 1 comment
Open

Add price_history #219

antoinebou12 opened this issue Aug 20, 2024 · 1 comment
Assignees
Labels
good first issue Good for newcomers help wanted Extra attention is needed

Comments

@antoinebou12
Copy link
Owner

antoinebou12 commented Aug 20, 2024


import httpx
import json

def fetch_price_history(ticker: str, timeframe: str, start_date: int, end_date: int):
    url = "https://api.wsj.net/api/michelangelo/timeseries/history"

    # Define the query parameters
    params = {
        "json": json.dumps({
            "Step": timeframe,
            "TimeFrame": timeframe,
            "StartDate": start_date,
            "EndDate": end_date,
            "EntitlementToken": "cecc4267a0194af89ca343805a3e57af",
            "IncludeMockTick": True,
            "FilterNullSlots": False,
            "FilterClosedPoints": True,
            "IncludeClosedSlots": False,
            "IncludeOfficialClose": True,
            "InjectOpen": False,
            "ShowPreMarket": False,
            "ShowAfterHours": False,
            "UseExtendedTimeFrame": True,
            "WantPriorClose": False,
            "IncludeCurrentQuotes": False,
            "ResetTodaysAfterHoursPercentChange": False,
            "Series": [
                {
                    "Key": f"STOCK/US/XNAS/{ticker.upper()}",
                    "Dialect": "Charting",
                    "Kind": "Ticker",
                    "SeriesId": "s1",
                    "DataTypes": ["Last"],
                    "Indicators": [
                        {
                            "Parameters": [
                                {"Name": "Period", "Value": "50"}
                            ],
                            "Kind": "SimpleMovingAverage",
                            "SeriesId": "i2"
                        },
                        {
                            "Parameters": [],
                            "Kind": "Volume",
                            "SeriesId": "i3"
                        },
                        {
                            "Parameters": [
                                {"Name": "EMA1", "Value": 12},
                                {"Name": "EMA2", "Value": 26},
                                {"Name": "SignalLine", "Value": 9}
                            ],
                            "Kind": "MovingAverageConvergenceDivergence",
                            "SeriesId": "i4"
                        },
                        {
                            "Parameters": [
                                {"Name": "YearOverYear"}
                            ],
                            "Kind": "EarningsEvents",
                            "SeriesId": "i5"
                        },
                        {
                            "Parameters": [],
                            "Kind": "DividendEvents",
                            "SeriesId": "i6"
                        },
                        {
                            "Parameters": [],
                            "Kind": "SplitEvents",
                            "SeriesId": "i7"
                        }
                    ]
                }
            ]
        }),
        "ckey": "cecc4267a0"
    }

    # Set headers similar to your browser's request
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.6478.57 Safari/537.36",
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "Dylan2010.entitlementtoken": "cecc4267a0194af89ca343805a3e57af",
        "Origin": "https://www.marketwatch.com",
        "Sec-Fetch-Site": "cross-site",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Dest": "empty",
        "Referer": f"https://www.marketwatch.com/investing/stock/{ticker.lower()}/charts?mod=mw_quote_advanced",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "en-US",
    }

    # Make the GET request
    try:
        with httpx.Client(http2=True) as client:
            response = client.get(url, params=params, headers=headers)
            response.raise_for_status()  # Check for HTTP errors
            return response.json()  # Parse JSON response

    except httpx.HTTPStatusError as err:
        print(f"HTTP error occurred: {err}")
    except Exception as err:
        print(f"Other error occurred: {err}")

if __name__ == "__main__":
    # Example usage
    ticker = "AAPL"  # Replace with your desired stock ticker
    timeframe = "P1D"  # Replace with your desired timeframe (e.g., "P1D" for daily data)
    start_date = 1692489600000  # Replace with your desired start date (in Unix timestamp)
    end_date = 1724112000000  # Replace with your desired end date (in Unix timestamp)

    stock_data = fetch_price_history(ticker, timeframe, start_date, end_date)
    if stock_data:
        print(json.dumps(stock_data, indent=4))
import httpx
import json
import logging

logging.basicConfig(level=logging.INFO)

def build_series(ticker: str, indicators: list) -> dict:
    """
    Build the series dictionary for the given ticker and indicators.

    :param ticker: The stock ticker (e.g., "AAPL").
    :param indicators: A list of indicators with their parameters.
    :return: The series dictionary to include in the API request.
    """
    return {
        "Key": f"STOCK/US/XNAS/{ticker.upper()}",
        "Dialect": "Charting",
        "Kind": "Ticker",
        "SeriesId": "s1",
        "DataTypes": ["Last"],
        "Indicators": indicators
    }

def build_indicator(kind: str, parameters: list = None, series_id: str = None) -> dict:
    """
    Build an indicator dictionary for a given kind and its parameters.

    :param kind: The kind of indicator (e.g., "SimpleMovingAverage").
    :param parameters: A list of parameters for the indicator (optional).
    :param series_id: A unique ID for the indicator series (optional).
    :return: The indicator dictionary.
    """
    return {
        "Parameters": parameters if parameters else [],
        "Kind": kind,
        "SeriesId": series_id if series_id else f"i{len(kind)}"
    }

def fetch_price_history(ticker: str, step: str, timeframe: str, start_date: int, end_date: int, indicators: list, hash_value: str):
    """
    Fetch historical stock price data for a given ticker using the MarketWatch API.

    :param ticker: The stock ticker (e.g., "AAPL").
    :param step: The data step interval (e.g., "PT5M" for 5-minute intervals).
    :param timeframe: The timeframe (e.g., "D1" for 1 day).
    :param start_date: The start date in Unix timestamp format.
    :param end_date: The end date in Unix timestamp format.
    :param indicators: A list of indicators to include in the series.
    :param hash_value: The hash value for the request.
    :return: The historical stock data as a dictionary.
    """
    url = "https://api.wsj.net/api/michelangelo/timeseries/history"

    # Build the request payload
    payload = {
        "Step": step,
        "TimeFrame": timeframe,
        "StartDate": start_date,
        "EndDate": end_date,
        "EntitlementToken": "cecc4267a0194af89ca343805a3e57af",
        "IncludeMockTick": True,
        "FilterNullSlots": False,
        "FilterClosedPoints": True,
        "IncludeClosedSlots": False,
        "IncludeOfficialClose": True,
        "InjectOpen": False,
        "ShowPreMarket": False,
        "ShowAfterHours": False,
        "UseExtendedTimeFrame": True,
        "WantPriorClose": False,
        "IncludeCurrentQuotes": False,
        "ResetTodaysAfterHoursPercentChange": False,
        "Series": [build_series(ticker, indicators)]
    }

    # Set headers similar to your browser's request
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.6478.57 Safari/537.36",
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "Content-Type": "application/json; charset=UTF-8",
        "Dylan2010.entitlementtoken": "cecc4267a0194af89ca343805a3e57af",
        "Origin": "https://www.marketwatch.com",
        "Sec-Fetch-Site": "cross-site",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Dest": "empty",
        "Referer": f"https://www.marketwatch.com/investing/stock/{ticker.lower()}/charts?mod=mw_quote_advanced",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "en-US",
    }

    # Define query parameters with hash and ckey
    params = {
        "hash": hash_value,
        "ckey": "cecc4267a0"
    }

    # Make the POST request
    try:
        with httpx.Client(http2=True) as client:
            response = client.post(url, params=params, json=payload, headers=headers)
            response.raise_for_status()  # Check for HTTP errors
            return response.json()  # Parse JSON response

    except httpx.HTTPStatusError as err:
        logging.error(f"HTTP error occurred: {err}")
    except Exception as err:
        logging.error(f"Other error occurred: {err}")

if __name__ == "__main__":
    # Example usage
    ticker = "AAPL"  # Replace with your desired stock ticker
    step = "PT5M"  # Replace with your desired data step interval (e.g., "PT5M" for 5-minute intervals)
    timeframe = "D1"  # Replace with your desired timeframe (e.g., "D1" for daily data)
    start_date = 1692489600000  # Replace with your desired start date (in Unix timestamp)
    end_date = 1724112000000  # Replace with your desired end date (in Unix timestamp)
    hash_value = "-392627967"  # Replace with your desired hash value

    # Define indicators to include
    indicators = [
        build_indicator("SimpleMovingAverage", [{"Name": "Period", "Value": "50"}]),
        build_indicator("Volume"),
        build_indicator("MovingAverageConvergenceDivergence", [
            {"Name": "EMA1", "Value": 12},
            {"Name": "EMA2", "Value": 26},
            {"Name": "SignalLine", "Value": 9}
        ]),
        build_indicator("BollingerBands", [
            {"Name": "Period", "Value": 20},
            {"Name": "Multiplier", "Value": 2}
        ])
    ]

    stock_data = fetch_price_history(ticker, step, timeframe, start_date, end_date, indicators, hash_value)
    if stock_data:
        print(json.dumps(stock_data, indent=4))
        
@antoinebou12 antoinebou12 self-assigned this Aug 20, 2024
Copy link

Branch issue-219-Add_price_history created!

@antoinebou12 antoinebou12 added help wanted Extra attention is needed good first issue Good for newcomers labels Aug 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
good first issue Good for newcomers help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant