Giter Club home page Giter Club logo

yahoo-finance-api's Introduction

scheb/yahoo-finance-api

This is a PHP client for Yahoo Finance API.

Build Status Code Coverage Latest Stable Version Total Downloads License

Logo

Since YQL APIs have been discontinued in November 2017, this client is using non-official API endpoints for quotes, search and historical data.

⚠️ WARNING: These non-official APIs cannot be assumed stable and might break any time. Also, you might violate Yahoo's terms of service. So use them at your own risk.

Installation

Download via Composer:

composer require scheb/yahoo-finance-api

Alternatively you can also add the package directly to composer.json:

{
    "require": {
        "scheb/yahoo-finance-api": "^4.0"
    }
}

and then tell Composer to install the package:

composer update scheb/yahoo-finance-api

Usage

use Scheb\YahooFinanceApi\ApiClient;
use Scheb\YahooFinanceApi\ApiClientFactory;
use GuzzleHttp\Client;

// Create a new client from the factory
$client = ApiClientFactory::createApiClient();

// Or use your own Guzzle client and pass it in
$options = [/* ... */];
$guzzleClient = new Client($options);
$client = ApiClientFactory::createApiClient($guzzleClient);

// Returns an array of Scheb\YahooFinanceApi\Results\SearchResult
$searchResult = $client->search("Apple");

// Returns an array of Scheb\YahooFinanceApi\Results\HistoricalData
$historicalData = $client->getHistoricalQuoteData(
    "AAPL",
    ApiClient::INTERVAL_1_DAY,
    new \DateTime("-14 days"),
    new \DateTime("today")
);

// Retrieve dividends history, returns an array of Scheb\YahooFinanceApi\Results\DividendData
$dividendData = $client->getHistoricalDividendData(
    "AAPL",
    new \DateTime("-5 years"),
    new \DateTime("today")
);

// Retrieve stock split history, returns an array of Scheb\YahooFinanceApi\Results\SplitData
$splitData = $client->getHistoricalSplitData(
    "AAPL",
    new \DateTime("-5 years"),
    new \DateTime("today")
);

// Returns Scheb\YahooFinanceApi\Results\Quote
$exchangeRate = $client->getExchangeRate("USD", "EUR");

// Returns an array of Scheb\YahooFinanceApi\Results\Quote
$exchangeRates = $client->getExchangeRates([
    ["USD", "EUR"],
    ["EUR", "USD"],
]);

// Returns Scheb\YahooFinanceApi\Results\Quote
$quote = $client->getQuote("AAPL");

// Returns an array of Scheb\YahooFinanceApi\Results\Quote
$quotes = $client->getQuotes(["AAPL", "GOOG"]);

// Returns an array of Scheb\YahooFinanceApi\Results\OptionChain
$optionChain = $client->getOptionChain("AAPL");
$optionChain = $client->getOptionChain("AAPL", new \DateTime("2021-01-01"));

Version Guidance

Version Status PHP Version
1.x EOL >= 5.3.0
2.x EOL >= 5.6.0
3.x EOL >= 5.6.0
4.x Maintained >= 7.1.3

License

This library is available under the MIT license.

Contributing

Want to contribute to this project? See CONTRIBUTING.md.

Support Me

I'm developing this library since 2014. I love to hear from people using it, giving me the motivation to keep working on my open source projects.

If you want to let me know you're finding it useful, please consider giving it a star ⭐ on GitHub.

If you love my work and want to say thank you, you can help me out for a beer 🍻️ via PayPal.

yahoo-finance-api's People

Contributors

abramovvyacheslav avatar benjaminpaap avatar clind922 avatar compotypo avatar elminson avatar hackeresq avatar peter279k avatar scheb avatar spomky avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yahoo-finance-api's Issues

Ex-Dividend Date

Firstly, thanks very much for your effort building this API, I've been using it a lot in my project. I've scoured through the source code and I don't seem to see the ex-dividend date being populated in the GetQuote procedure. I'm not sure if this is technically possible but on the quote pages on the front end I can see "Ex-Dividend Date" being shown.

Let me know if this feature is a possibility as I'd like to be able to create a calendar of all my stock's upcoming ex-dividend dates.

Thanks!

429 Too Many Requests

We get the same error from two different servers. Error 429 Too Many Requests returns when pulling data..

No problem on link: https://query1.finance.yahoo.com/v1/test/getcrumb

Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: GET https://query2.finance.yahoo.com/v1/test/getcrumb resulted in a 429 Too Many Requests response: Too Many Requests in /home/mytrnuwm/public_html/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113 Stack trace: #0 /home/mytrnuwm/public_html/vendor/guzzlehttp/guzzle/src/Middleware.php(65): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response)) #1 /home/mytrnuwm/public_html/vendor/guzzlehttp/promises/src/Promise.php(204): GuzzleHttp\Middleware::GuzzleHttp{closure}(Object(GuzzleHttp\Psr7\Response)) #2 /home/mytrnuwm/public_html/vendor/guzzlehttp/promises/src/Promise.php(153): GuzzleHttp\Promise\Promise::callHandler(1, Object(GuzzleHttp\Psr7\Response), NULL) #3 /home/mytrnuwm/public_html/vendor/guzzlehttp/promises/src/TaskQueue.php(48): GuzzleHttp\Promise\Promise::GuzzleHttp\Promise{closure}() #4 /home/mytrnuwm/public_html/vendor/guzzlehttp/promises/src/Promise.php(248): Gu in /home/mytrnuwm/public_html/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php on line 113

Statistics Tab

I've checked the code and it doesn't look like the "Statistics" tab data is queryable for a stock.

Is the data on this page able to be returned? I'm trying to access data in the balance sheet for Total Debt/Equity (mrq).

Thanks again love your work!

HTTP 404

not a bug.
when seaching quote for a society whose quotation has ceased, with :
$quote = $client->getHistoricalQuoteData("KORI.PA",ApiClient::INTERVAL_1_DAY,new \DateTime("2020-02-10"),new \DateTime("today"));
i get HTTP 404 error, like this :
Client error: GET https://query1.finance.yahoo.com/v7/finance/download/KORI.PA?period1=1581289200&period2=1705359600&interval=1d&events=history``
How can i manage this error and thus avoiding php script interrupt during a loop thru list of societies ?
(Error occurs even param "end_date" of GetHistoricalQuoteData is set to cease_date).
Thanks
Eric

HistoricalData

Did Yahoo remove the historicalData portion of their query?

Yahoo Finance GuzzleHTTP Exception is Recurring on V6 Endpoint

PHP Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: GET https://query1.finance.yahoo.com/v6/finance/quote?symbols=%5EIXIC%2C%5EDJI%2C%5EGSPC%2C%5ERUT%2CABCL%2CASGN%2CAVO%2CCRCT%2CDEI%2CDINO%2CEPAM%2CGEN%2CGHL%2CINZY%2CLKFN resulted in a 404 Not Found response:
{"finance":{"result":null,"error":{"code":"Not Found","description":"HTTP 404 Not Found"}}}

Directory and class names in lower case

May I suggest to have the directory names and class names to be in lower case? This is needed for spl_autoload_register() to be able to find classes inside the directory structure. You already have name spaces matching the directory structure, which is great. Thank you for your code!

getQuotes with a invalid symbol

When using $client->getQuotes($symbols), if one of the symbols is invalid or Yahoo don't have information about, the class will just skip it, so if I sent an array with 20 elements, I may get a return with only 18 elements.

I would like to suggest one of this options as a solution:

  • Make the resulted array have keys instead of an index only, maybe the symbol as a key
  • Instead of skipping it, it could add a new array element with an error message for that symbol

I'm not sure if I expressed myself well enough, but if not, please send me questions so I can clarify.

Thanks!

V6 API endpoint 404

Package version: 4.6.0

Description

When using the getQuotes(array $symbols) function, it throw out the following error

  Client error: `GET https://query1.finance.yahoo.com/v6/finance/quote?symbols=%5ERUT` resulted in a `404 Not Found` response:
{"finance":{"result":null,"error":{"code":"Not Found","description":"HTTP 404 Not Found"}}}

To Reproduce

Steps to reproduce the behavior:

  1. Create a new APIClient instance
  2. call $client->getQuotes(["^RUT"])
  3. See error
   GuzzleHttp\Exception\ClientException 

  Client error: `GET https://query1.finance.yahoo.com/v6/finance/quote?symbols=%5ERUT` resulted in a `404 Not Found` response:
{"finance":{"result":null,"error":{"code":"Not Found","description":"HTTP 404 Not Found"}}}

  at vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113
    109▕         if ($summary !== null) {
    110▕             $message .= ":\n{$summary}\n";
    111▕         }
    112▕ 
  ➜ 113▕         return new $className($message, $request, $response, $previous, $handlerContext);
    114▕     }
    115▕ 
    116▕     /**
    117▕      * Obfuscates URI if there is a username and a password present


Additional Context

This stopped working about 5 hrs ago (Tuesday, May 23, 2023 10:30:00 PM UTC)
Was working with out any problem before that.

Invalid Cookie

https://github.com/scheb/yahoo-finance-api)

HI, Thank you so much for the work yu have done to keep Yahoo finance accessible. I don't have the version no for this script. I have been running it successfuly for several years but today it failed as follows.

Uncaught GuzzleHttp\Exception\ClientException: Client error: GET https://query1.finance.yahoo.com/v7/finance/quote?symbols=%5EIXIC%2C%5EDJI%2C%5EGSPC%2C%5ERUT%2CAKRO%2CAQN%2CBCRX%2CBTAI%2CCCOI%2CCOCO%2CGPOR%2CGRBK%2CHEAR%2CPAGS%2CTFX resulted in a 401 Unauthorized response:
{"finance":{"result":null,"error":{"code":"Unauthorized","description":"Invalid Cookie"}}}

Your help would be very much appreciated.

getQuote() fails

Hey :)

getQuote() seems to throw back the following error:

PHP Warning: array_map(): Argument #2 should be an array in /Applications/MAMP/htdocs/asxlink/vendor/scheb/yahoo-finance-api/src/ResultDecoder.php

even though the unofficial API's are still active.

search() and getHistoricalData() are still working fine.

Server Error 500 on echo Object

Hi!
Thanks for create Great API. Its working fine but I don't know why its causing issue for me.
I am using PHP 7.1 but for some object when I try to echo, I am getting error 500 on server and do not getting value for it.
echo $quote->getAsk().'
';
echo $quote->getAskSize().'
';
its working fine
but when I run something like
echo $quote->getFiftyTwoWeekHighChange()().'High Change
';
echo $quote->getFiftyTwoWeekHighChangePercent()().'
';
echo $quote->getFiftyTwoWeekLow()().'
';
its not returning any value and in network tab, I can see error 500, However I am able to get this values when I print_r($quote); without any issue and error, I am missing something?
Thanks!

Bulk Insert of historical data - how to access private members?

Proposal to amend code to allow bulk inserts

I would like to do a bulk insert of historical data. This is trivial using Laravel's Query helper:

$client = Scheb\YahooFinanceApi\ApiClientFactory::createApiClient();
$historicalPricing = $client->getHistoricalQuoteData(
  "msft",
  Scheb\YahooFinanceApi\ApiClient::INTERVAL_1_DAY,
  new \DateTime("-1 year"),
  new \DateTime("today")
);

DB::table("share_price_histories")->insert($newArray);

However, since ->getHistoricalQuoteData returns results as private members I'm lost as how to do it.

I could technically run for-next loop and convert everything to a new array, and then insert it, but having the for-next loop seems like a penalty.

I'm happy to do a pull request but I will need some guidance.

In theory one could make all the members as public access but I guess this will break some programming discipline.

Any assistance will be appreciated on how I could go about doing this.

The conditions in transformSearchResult and transformQuotes are strange

As title. Consider the following two conditions:

// Scheb\YahooFinanceApi\ResultDecoder::transformSearchResult

if (!isset($decoded['data']['items']) && is_array($decoded['data']['items'])) {
    throw new ApiException("Yahoo Search API returned an invalid response", ApiException::INVALID_RESPONSE);
}
//Scheb\YahooFinanceApi\ResultDecoder::transformQuotes

if (!isset($decoded['quoteResponse']['result']) && is_array($decoded['quoteResponse']['result'])) {
    throw new ApiException("Yahoo Search API returned an invalid result.", ApiException::INVALID_RESPONSE);
}

These two conditions will not be triggered because it's not a array value can be empty and array type at the same time. The empty array [] is true when passing to the isset function.
I think it's the bug. My suggestion that it should be changed into the following condition block:

if (empty($decoded['quoteResponse']['result'])) {
    // throw related Exceptions...
}
if (!isset($decoded['data']['items']) || is_array($decoded['data']['items'])) {
    // throw related Exceptions...
}

Yahoo.finance.quotes not exist

Hello.

Table yahoo.finance.quotes doesn't exist (renamed or changed to pm.finance). But pm.finance needed in additional permissions.

Maybe you know how to auth webapp in yql app by api?

Statistics tab

Hallo Christian,

I've just started playing around with your package and like it. Thank you!
I've managed to get basic quote information such as trailing PE, however I fail to access the information that is found on the statistics page such as payout ratio. Looking at past issues, I have found #35 which is marked as completed, however I fail to fi
/nd any of it in the source code.

Also the query link shared, fails with

{
    "finance": {
        "result": null,
        "error": {
            "code": "Unauthorized",
            "description": "Invalid Crumb"
        }
    }
}

Update: I actually figured it out, adding &crumb=mdeVssfeRhi to the request url works. I got the crumb value from a browser session on yahoo finance.

Get Historical Data Parameter Problem

$data = $client->getHistoricalData("YHOO");

  • Requires more parameters

$start = new DateTime('2014-01-02');
$end = new DateTime('2014-01-05');
$data = $client->getHistoricalData("YHOO",$start,$end);

Fatal error: Uncaught Scheb\YahooFinanceApi\Exception\HttpException: HTTP call failed with error 0

I'm not sure if you're still working on this app, however, thank you for it!

incomes

Why not add a function to download the incomes?
Not many people would use the historical function without also needing to get the incomes.
Thank you for your code.
cheers.

Expand the readme file

The readme file is extremely technical. Please expand the usage instructions so that people who are not familiar with Composer can still use this tool.

Can you use this code outside of Composer?

Could not extract crumb from response

Hi,

I'll get the folllowing error while getting historical data.

#4 {main}exception 'Scheb\YahooFinanceApi\Exception\ApiException' with message 'Could not extract crumb from response' in /vendor/scheb/yahoo-finance-api/src/ResultDecoder.php:128
Stack trace:
#0 /vendor/scheb/yahoo-finance-api/src/ApiClient.php(77): Scheb\YahooFinanceApi\ResultDecoder->extractCrumb('...')

Fatal error: Uncaught Error: Class 'Scheb\YahooFinanceApi\ApiClientFactory' not found

Hello,

I have a problem. I installed scheb using composer commands (note that I'm not with it).
So I did
composer require scheb/yahoo-finance-api

And
composer update scheb/yahoo-finance-api

Then I created a test.php in my root folder with :

<?php
use Scheb\YahooFinanceApi\ApiClient;
use Scheb\YahooFinanceApi\ApiClientFactory;
use GuzzleHttp\Client;

// Create a new client from the factory
$client = ApiClientFactory::createApiClient();



// Returns an array of Scheb\YahooFinanceApi\Results\SearchResult
$searchResult = $client->search("Apple");

// Returns an array of Scheb\YahooFinanceApi\Results\HistoricalData
$historicalData = $client->getHistoricalQuoteData(
    "AAPL",
    ApiClient::INTERVAL_1_DAY,
    new \DateTime("-14 days"),
    new \DateTime("today")
);

print_r($historicalData);exit; ?>

But i got the following errors :
Fatal error: Uncaught Error: Class 'Scheb\YahooFinanceApi\ApiClientFactory' not found in C:\wamp64\www\index.php on line 9
( ! ) Error: Class 'Scheb\YahooFinanceApi\ApiClientFactory' not found in C:\wamp64\www\index.php on line 9

Can you help me please ?

why is env => datatables needed to build query in creaturl?

do i need to pass this parameter? is there an alternative, when datatables org is down!?

createUrl($query)
    {
        $params = array(
            'env' => "http://datatables.org/alltables.env",
            'format' => "json",
            'q' => $query,
        );
        return "http://query.yahooapi
}```

Average Volume Getting Wrong Value

Hi!
Thanks for create a great API. I am using it and its working fine. However I have issue in Average Volume.
I am trying to fetch data of
https://finance.yahoo.com/quote/SAFE?p=SAFE

  1. in web portal average volume showing 106,239 but in our API response, its giving me 107524 I am not getting idea why its happening. Let me know if anyone here can help me about same.
  2. in web portal Ex-Dividend Date is Dec 30, 2020 but in our response I am getting [dividendDate:Scheb\YahooFinanceApi\Results\Quote:private] => DateTime Object ( [date] => 2021-01-15 00:00:00.000000 [timezone_type] => 1 [timezone] => +00:00 )
    Thanks a lot!

WKN / ISIN

Gibt es auch die Möglichkeit über die WKN zu suchen?

Wenn man nach dem Namen einer Aktien sucht, wäre es auch gut wenn im Ergebnis zusätzlich die ISIN stehen würde. Ist das möglich?

Error 404

"scheb/yahoo-finance-api": "4.x-dev"

Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: GET https://query2.finance.yahoo.com/v7/finance/download/0P00011HBL.F?period1=1692354296&period2=1692403200&interval=1d&events=history resulted in a 404 Not Found response: 404 Not Found: Timestamp data missing

Cannot install the package via Composer

Hi, the package could not be installed via Composer as of date because it requires Guzzle 6.x, but at this moment Guzzle released version 7 already. Please fix the error, thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.