Yahoo Finance URL无效

时间:2017-05-17 17:06:25

标签: yahoo-finance

我一直在使用以下网址从雅虎财经获取历史数据已有一段时间了,但截至昨天它已停止工作。

https://ichart.finance.yahoo.com/table.csv?s=SPY

浏览本网站时说:

  

马上回来......

     

感谢您的耐心等待。

     

我们的工程师正在迅速解决这个问题。

但是,由于这个问题自昨天起仍然存在,我开始认为他们已经停止了这项服务?

我的SO搜索仅指向this topic,这与https虽然相关......

还有其他人遇到此问题吗? 我该如何解决这个问题?他们是否提供对历史数据的不同访问权限?

25 个答案:

答案 0 :(得分:37)

看起来他们已经开始添加必需的Cookie,但您可以相当轻松地检索它,例如:

GET https://uk.finance.yahoo.com/quote/AAPL/history

回复表单中的标题:

set-cookie:B=xxxxxxxx&b=3&s=qf; expires=Fri, 18-May-2018 00:00:00 GMT; path=/; domain=.yahoo.com

您应该可以阅读此内容并将其附加到.csv请求中:

GET https://query1.finance.yahoo.com/v7/finance/download/AAPL?period1=1492524105&period2=1495116105&interval=1d&events=history&crumb=tO1hNZoUQeQ
cookie: B=xxxxxxxx&b=3&s=qf;

请注意crumb查询参数,这似乎与您cookie的某种方式相对应。您最好的选择是从您对初始GET请求的HTML响应中scrape这个。在该响应中,您可以执行正则表达式搜索:"CrumbStore":\{"crumb":"(?<crumb>[^"]+)"\}并提取crumb匹配组。

看起来,只要您拥有crumb值,虽然您可以在明年的任何符号/代码上使用相同的cookie,这意味着您不应该{ {1}}过于频繁。

要获取当前报价,只需加载:

scrape

使用:

  • AAPL替换为您的股票代码
  • https://query1.finance.yahoo.com/v8/finance/chart/AAPL?interval=2m
  • 的间隔时间
  • 带有您的纪元范围开始日期的可选[1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo]查询参数,例如period1
  • 带有您的纪元范围结束日期的可选period1=1510340760查询参数,例如period2

答案 1 :(得分:26)

Yahoo已进入Reactjs前端,这意味着如果您分析从客户端到后端的请求标头,您可以获得他们用来填充客户端商店的实际JSON。

主机:

如果您打算使用代理或持久连接,请使用query2.finance.yahoo.com。但就本文而言,用于示例网址的主机并不意味着暗示与其一起使用的路径。

基本数据

  • /v10/finance/quoteSummary/AAPL?modules=(以下模块的完整列表)

(将您的符号替换为:AAPL)

?modules=查询的输入:

  • modules = [ 'assetProfile', 'incomeStatementHistory', 'incomeStatementHistoryQuarterly', 'balanceSheetHistory', 'balanceSheetHistoryQuarterly', 'cashflowStatementHistory', 'cashflowStatementHistoryQuarterly', 'defaultKeyStatistics', 'financialData', 'calendarEvents', 'secFilings', 'recommendationTrend', 'upgradeDowngradeHistory', 'institutionOwnership', 'fundOwnership', 'majorDirectHolders', 'majorHoldersBreakdown', 'insiderTransactions', 'insiderHolders', 'netSharePurchaseActivity', 'earnings', 'earningsHistory', 'earningsTrend', 'industryTrend', 'indexTrend', 'sectorTrend' ]

示例网址

  • https://query1.finance.yahoo.com/v10/finance/quoteSummary/AAPL?modules=assetProfile%2CearningsHistory

查询assetProfileearningsHistory

%2C,的十六进制表示,需要在您请求的每个模块之间插入。 details about the hex encoding bit(如果你关心的话)

期权合约

  • /v7/finance/options/AAPL(当前到期日)
  • /v7/finance/options/AAPL?date=1579219200(2020年1月17日到期)

示例网址

  • https://query2.yahoo.finance.com/v7/finance/options/AAPL(当前到期日)
  • https://query2.yahoo.finance.com/v7/finance/options/AAPL?date=1579219200(2020年1月17日到期)

可以在?date=查询中使用表示为UNIX时间戳的任何有效的未来到期时间。如果查询当前过期,则JSON响应将包含可在?date=查询中使用的所有有效过期的列表。 (here is a post explaining converting human readable dates to unix timestamp in Python)

价格

  • /v8/finance/chart/AAPL?symbol=AAPL&period1=0&period2=9999999999&interval=3mo

<强>间隔:

  • &interval=3mo 3个月,回到最初的交易日期。
  • &interval=1d 1天,回到最初的交易日期。
  • &interval=5m 5分钟,回到80(ish)天。
  • &interval=1m 1小时,回到4-5天。

每个间隔你能走多远,有点混乱,似乎不一致。我的假设是内部雅虎在交易日计算,而我的天真方法并不是假期。虽然这是一个猜测和YMMV。

period1=:您希望开始的日期的unix时间戳表示。低于初始交易日的价值将四舍五入到初始交易日。

period2=:您希望结束的日期的unix时间戳表示。大于上次交易日期的值将向下舍入到最新的可用时间戳。

注意: 如果您使用的period1=(开始日期)在您选择的时间间隔内查询过多,yahoo将返回价格在3mo间隔内,无论您请求的间隔是什么。

添加pre&amp;发布市场数据

&includePrePost=true

添加红利&amp;分割

&events=div%2Csplit

示例网址

  • https://query1.finance.yahoo.com/v8/finance/chart/AAPL?symbol=AAPL&period1=0&period2=9999999999&interval=1d&includePrePost=true&events=div%2Csplit

上述请求将在1天的时间间隔内返回股票代码AAPL的所有价格数据,包括市场前和后市场数据以及股息和拆分。

注意: period1=&amp;的价格示例网址中使用的值period2=用于演示每个输入的相应舍入行为。

答案 2 :(得分:18)

我成功地设计了一个.NET类来从Yahoo Finance获得有效的令牌(cookie和crumb)

要从新的Yahoo Finance获取历史数据的完整API库,您可以访问Github中的YahooFinanceAPI

这是获取cookie和crumb的类

<强> Token.cs

using System;
using System.Diagnostics;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace YahooFinanceAPI
{
    /// <summary>
    /// Class for fetching token (cookie and crumb) from Yahoo Finance
    /// Copyright Dennis Lee
    /// 19 May 2017
    /// 
    /// </summary>
    public class Token
    {
        public static string Cookie { get; set; }
        public static string Crumb { get; set; }

        private static Regex regex_crumb;
        /// <summary>
        /// Refresh cookie and crumb value Yahoo Fianance
        /// </summary>
        /// <param name="symbol">Stock ticker symbol</param>
        /// <returns></returns>
        public static bool Refresh(string symbol = "SPY")
        {

            try
            {
                Token.Cookie = "";
                Token.Crumb = "";

                string url_scrape = "https://finance.yahoo.com/quote/{0}?p={0}";
                //url_scrape = "https://finance.yahoo.com/quote/{0}/history"

                string url = string.Format(url_scrape, symbol);

                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

                request.CookieContainer = new CookieContainer();
                request.Method = "GET";

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {

                    string cookie = response.GetResponseHeader("Set-Cookie").Split(';')[0];

                    string html = "";

                    using (Stream stream = response.GetResponseStream())
                    {
                        html = new StreamReader(stream).ReadToEnd();
                    }

                    if (html.Length < 5000)
                        return false;
                    string crumb = getCrumb(html);
                    html = "";

                    if (crumb != null)
                    {
                        Token.Cookie = cookie;
                        Token.Crumb = crumb;
                        Debug.Print("Crumb: '{0}', Cookie: '{1}'", crumb, cookie);
                        return true;
                    }

                }

            }
            catch (Exception ex)
            {
                Debug.Print(ex.Message);
            }

            return false;

        }

        /// <summary>
        /// Get crumb value from HTML
        /// </summary>
        /// <param name="html">HTML code</param>
        /// <returns></returns>
        private static string getCrumb(string html)
        {

            string crumb = null;

            try
            {
                //initialize on first time use
                if (regex_crumb == null)
                    regex_crumb = new Regex("CrumbStore\":{\"crumb\":\"(?<crumb>.+?)\"}", 
                RegexOptions.CultureInvariant | RegexOptions.Compiled, TimeSpan.FromSeconds(5));

                MatchCollection matches = regex_crumb.Matches(html);

                if (matches.Count > 0)
                {
                    crumb = matches[0].Groups["crumb"].Value;
                }
                else
                {
                    Debug.Print("Regex no match");
                }

                //prevent regex memory leak
                matches = null;

            }
            catch (Exception ex)
            {
                Debug.Print(ex.Message);
            }

            GC.Collect();
            return crumb;

        }

    }
}

17月6日更新
归功于@ Ed0906
将crumb正则表达式模式修改为Regex("CrumbStore\":{\"crumb\":\"(?<crumb>.+?)\"}"

答案 3 :(得分:13)

在此论坛中:https://forums.yahoo.net/t5/Yahoo-Finance-help/Is-Yahoo-Finance-API-broken/td-p/250503/page/3

尼克松说:

  

大家好 - 此功能已由财务团队停止,他们不会重新引入该功能。

答案 4 :(得分:10)

对于那里的python爱好者,我已经更新了tradeWithPython库中的yahooFinance.py

还有一个基于Ed0906提示的示例notebook,演示了如何逐步获取数据。

答案 5 :(得分:10)

下载历史数据的URL现在是这样的:

https://query1.finance.yahoo.com/v7/finance/download/SPY?period1=1492449771&period2=1495041771&interval=1d&events=history&crumb=9GaimFhz.WU

请注意,上述网址不适合您或其他任何人。你会得到这样的东西:

{
    "finance": {
        "error": {
            "code": "Unauthorized",
            "description": "Invalid cookie"
        }
    }
}

雅虎现在似乎正在使用一些哈希来阻止人们像你一样访问数据。网址因每个会话而异,因此您很可能不再使用固定网址执行此操作。

您需要进行一些报废才能从主页面获取正确的网址,例如:

https://finance.yahoo.com/quote/SPY/history?p=SPY

答案 6 :(得分:5)

我找到了另一个不需要cookie的雅虎网站,但产生了jason输出:https://query1.finance.yahoo.com/v7/finance/chart/YHOO?range=2y&interval=1d&indicators=quote&includeTimestamps=true

从这里指出:https://www.stock-data-solutions.com/kb/how-to-load-historical-prices-from-yahoo-finance-to-excel.htm

事实证明,它们似乎支持'perod1'和'period2'(在unix时间内)参数,可以用来代替'interval'。

String quoteSite = "https://query1.finance.yahoo.com/v7/finance/chart/"
                   + symbolName + "?"
                   + "period1=" + period1
                   + "&period2=" + period2
                   + "&interval=1d&indicators=quote&includeTimestamps=true";

以下解析Jason:

JSONObject topObj = new JSONObject(inp);
Object error = topObj.getJSONObject("chart").get("error");
if (!error.toString().equals("null")) {
    System.err.prinltn(error.toString());
    return null;
}
JSONArray results = topObj.getJSONObject("chart").getJSONArray("result");
if (results == null || results.length() != 1) {
    return null;
}
JSONObject result = results.getJSONObject(0);
JSONArray timestamps = result.getJSONArray("timestamp");
JSONObject indicators = result.getJSONObject("indicators");
JSONArray quotes = indicators.getJSONArray("quote");
if (quotes == null || quotes.length() != 1) {
    return null;
}
JSONObject quote = quotes.getJSONObject(0);
JSONArray adjcloses = indicators.getJSONArray("adjclose");
if (adjcloses == null || adjcloses.length() != 1) {
   return null;
}
JSONArray adjclose = adjcloses.getJSONObject(0).getJSONArray("adjclose");
JSONArray open = quote.getJSONArray("open");
JSONArray close = quote.getJSONArray("close");
JSONArray high = quote.getJSONArray("high");
JSONArray low = quote.getJSONArray("low");
JSONArray volume = quote.getJSONArray("volume");

答案 7 :(得分:5)

完全正常工作 PHP示例,基于此帖子和相关来源:

function readYahoo($symbol, $tsStart, $tsEnd) {
  preg_match('"CrumbStore\":{\"crumb\":\"(?<crumb>.+?)\"}"',
    file_get_contents('https://uk.finance.yahoo.com/quote/' . $symbol),
    $crumb);  // can contain \uXXXX chars
  if (!isset($crumb['crumb'])) return 'Crumb not found.';
  $crumb = json_decode('"' . $crumb['crumb'] . '"');  // \uXXXX to UTF-8
  foreach ($http_response_header as $header) {
    if (0 !== stripos($header, 'Set-Cookie: ')) continue;
    $cookie = substr($header, 14, strpos($header, ';') - 14);  // after 'B='
  }  // cookie looks like "fkjfom9cj65jo&b=3&s=sg"
  if (!isset($cookie)) return 'Cookie not found.';
  $fp = fopen('https://query1.finance.yahoo.com/v7/finance/download/' . $symbol
    . '?period1=' . $tsStart . '&period2=' . $tsEnd . '&interval=1d'
    . '&events=history&crumb=' . $crumb, 'rb', FALSE,
    stream_context_create(array('http' => array('method' => 'GET',
      'header' => 'Cookie: B=' . $cookie))));
  if (FALSE === $fp) return 'Can not open data.';
  $buffer = '';
  while (!feof($fp)) $buffer .= implode(',', fgetcsv($fp, 5000)) . PHP_EOL;
  fclose($fp);
  return $buffer;
}

<强>用法

$csv = readYahoo('AAPL', mktime(0, 0, 0, 6, 2, 2017), mktime(0, 0, 0, 6, 3, 2017));

答案 8 :(得分:5)

对于java爱好者。

您可以通过这种方式从URLConnection访问您的Cookie。

 //  "https://finance.yahoo.com/quote/SPY";
 URLConnection con = url.openConnection();
 ...  
 for (Map.Entry<String, List<String>> entry : con.getHeaderFields().entrySet()) {
        if (entry.getKey() == null 
            || !entry.getKey().equals("Set-Cookie"))
            continue;
        for (String s : entry.getValue()) {
           // store your cookie
           ...
        }
 }

现在你可以在雅虎网站上搜索crumb:

String crumb = null;
InputStream inStream = con.getInputStream();
InputStreamReader irdr = new InputStreamReader(inStream);
BufferedReader rsv = new BufferedReader(irdr);

Pattern crumbPattern = Pattern.compile(".*\"CrumbStore\":\\{\"crumb\":\"([^\"]+)\"\\}.*");

String line = null;
while (crumb == null && (line = rsv.readLine()) != null) {
    Matcher matcher = crumbPattern.matcher(line);
    if (matcher.matches()) 
        crumb = matcher.group(1);
}
rsv.close();

最后,设置cookie

String quoteUrl = "https://query1.finance.yahoo.com/v7/finance/download/IBM?period1=1493425217&period2=1496017217&interval=1d&events=history&crumb="
                           + crumb
...
List<String> cookies = cookieStore.get(key);
if (cookies != null) {
    for (String c: cookies) 
        con.setRequestProperty("Cookie", c);
}
...
con.connect();

答案 9 :(得分:5)

我在同一条船上。慢慢到达那里。历史价格页面上的下载链接仍然有效。所以我将导出cookie扩展添加到firefox,登录到yahoo,转储cookie。使用交互式会话中的crumb值,我能够检索值。这是测试perl脚本的一部分。

use Time::Local;

# create unix time variables for start and end date values: 1/1/2014 thru 12/31/2017
$p1= timelocal(0,0,0,1,0,114);
$p2= timelocal(0,0,0,31,11,117);

$symbol = 'AAPL';

# create variable for string to be executed as a system command
# cookies.txt exported from firefox
# crumb variable retrieved from yahoo download data link
$task = "wget --load-cookies cookies.txt --no-check-certificate -T 30 -O          $symbol.csv \"https://query1.finance.yahoo.com/v7/finance/download/$symbol?period1=$p1&period2=$p2&interval=1d&events=history&crumb=7WhHVu5N4e3\" ";

#show what we're executing
print $task;

# execute system command using backticks
`$task`;

#output is AAPL.csv

我需要一段时间来自动完成我的工作。希望雅虎能够简化或提供一些指导,如果他们真的打算让人们使用它。

答案 10 :(得分:4)

的Python

我使用此代码获取Cookie(从fix-yahoo-finance复制):

def get_yahoo_crumb_cookie():
    """Get Yahoo crumb cookie value."""
    res = requests.get('https://finance.yahoo.com/quote/SPY/history')
    yahoo_cookie = res.cookies['B']
    yahoo_crumb = None
    pattern = re.compile('.*"CrumbStore":\{"crumb":"(?P<crumb>[^"]+)"\}')
    for line in res.text.splitlines():
        m = pattern.match(line)
        if m is not None:
            yahoo_crumb = m.groupdict()['crumb']
    return yahoo_cookie, yahoo_crumb

然后这段代码得到回应:

cookie, crumb = get_yahoo_crumb_cookie()
params = {
    'symbol': stock.symbol,
    'period1': 0,
    'period2': int(time.time()),
    'interval': '1d',
    'crumb': crumb,
}
url_price = 'https://query1.finance.yahoo.com/v7/finance/download/{symbol}'

response = requests.get(url_price, params=params, cookies={'B': cookie})

这看起来很不错http://blog.bradlucas.com/posts/2017-06-03-yahoo-finance-quote-download-python/

答案 11 :(得分:3)

我使用了一个使用fopen()的php脚本来访问财务数据,以下是我修改后的片段,以使其恢复工作:

创建开始日期和结束日期的时间戳:

$timestampStart = mktime(0,0,0,$startMonth,$startDay,$startYear);
$timestampEnd = mktime(0,0,0,$endMonth,$endDay,$endYear);

强制fopen()发送带有硬编码值的必需cookie:

$cookie="YourCookieTakenFromYahoo";

$opts = array(
    'http'=>array(
        'method'=>"GET",
        'header'=>"Accept-language: en\r\n" .
            "Cookie: B=".$cookie."\r\n"
    )
);

$context = stream_context_create($opts);    

使用fopen()获取csv文件:

$ticker="TickerSymbol";
$crumb="CrumbValueThatMatchesYourCookieFromYahoo";

$handle = fopen("https://query1.finance.yahoo.com/v7/finance/download/".$ticker."?period1=".$timestampStart."&period2=".$timestampEnd."&interval=1d&events=history&crumb=".$crumb."", "r", false, $context);

现在你可以在这个while循环中做你所做的所有魔术:

while (!feof($handle) ) {
    $line_of_text = fgetcsv($handle, 5000);
}

请务必在上面的代码段中为$ticker$crumb$cookie设置自己的值。 关注如何检索$crumb$cookie

,请点击Ed0906's approach

答案 12 :(得分:3)

我是service

的作者

基本信息here

每日价格

您需要熟悉RESTFUL服务。

https://quantprice.herokuapp.com/api/v1.1/scoop/day?tickers=MSFT&date=2017-06-09

历史价格

您必须提供日期范围:

https://quantprice.herokuapp.com/api/v1.1/scoop/period?tickers=MSFT&begin=2012-02-19&end=2012-02-20

如果您不提供开始或结束,则会使用最早或当前日期:

https://quantprice.herokuapp.com/api/v1.1/scoop/period?tickers=MSFT&begin=2012-02-19

多个代码

你可以用逗号分隔代码:

https://quantprice.herokuapp.com/api/v1.1/scoop/period?tickers=IBM,MSFT&begin=2012-02-19

费率限制

所有请求的速率限制为每小时10个请求。如果你想注册一个完整的访问API,请在twitter上发送给我DM。您将收到一个API密钥以添加到URL。

我们正在为付费订阅设置一个paypal帐户,不含费率。

可用的代码列表

https://github.com/robomotic/valueviz/blob/master/scoop_tickers.csv

我也在努力提供EDGAR的基础数据和公司数据。 欢呼声。

答案 13 :(得分:3)

<强> VBA

以下是一些VBA函数,它们下载并解压缩cookie / crumb对并在Collection中返回这些函数,然后使用这些函数下载特定代码的csv文件内容。

包含项目应该引用“Microsoft XML,v6.0&#39;添加了库(其他版本也可能没什么问题,对代码进行一些细微的更改)。

Sub Test()
    Dim X As Collection

    Set X = FindCookieAndCrumb()

    Debug.Print X!cookie
    Debug.Print X!crumb

    Debug.Print YahooRequest("AAPL", DateValue("31 Dec 2016"), DateValue("30 May 2017"), X)
End Sub


Function FindCookieAndCrumb() As Collection
    ' Tools - Reference : Microsoft XML, v6.0
    Dim http    As MSXML2.XMLHTTP60
    Dim cookie  As String
    Dim crumb   As String
   Dim url     As String
    Dim Pos1    As Long
    Dim X       As String

    Set FindCookieAndCrumb = New Collection

    Set http = New MSXML2.ServerXMLHTTP60

    url = "https://finance.yahoo.com/quote/MSFT/history"

    http.Open "GET", url, False
    ' http.setProxy 2, "https=127.0.0.1:8888", ""
    ' http.setRequestHeader "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
    ' http.setRequestHeader "Accept-Encoding", "gzip, deflate, sdch, br"
    ' http.setRequestHeader "Accept-Language", "en-ZA,en-GB;q=0.8,en-US;q=0.6,en;q=0.4"
    http.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
    http.send

    X = http.responseText

    Pos1 = InStr(X, "CrumbStore")

    X = Mid(X, Pos1, 44)

    X = Mid(X, 23, 44)

    Pos1 = InStr(X, """")

    X = Left(X, Pos1 - 1)

    FindCookieAndCrumb.Add X, "Crumb"

    '======================================

    X = http.getResponseHeader("set-cookie")

    Pos1 = InStr(X, ";")

    X = Left(X, Pos1 - 1)

    FindCookieAndCrumb.Add X, "Cookie"

End Function

Function YahooRequest(ShareCode As String, StartDate As Date, EndDate As Date, CookieAndCrumb As Collection) As String
    ' Tools - Reference : Microsoft XML, v6.0
    Dim http            As MSXML2.XMLHTTP60
    Dim cookie          As String
    Dim crumb           As String
    Dim url             As String
    Dim UnixStartDate   As Long
    Dim UnixEndDate     As Long
    Dim BaseDate        As Date

    Set http = New MSXML2.ServerXMLHTTP60

    cookie = CookieAndCrumb!cookie
    crumb = CookieAndCrumb!crumb

    BaseDate = DateValue("1 Jan 1970")

    If StartDate = 0 Then StartDate = BaseDate

    UnixStartDate = (StartDate - BaseDate) * 86400
    UnixEndDate = (EndDate - BaseDate) * 86400

    url = "https://query1.finance.yahoo.com/v7/finance/download/" & ShareCode & "?period1=" & UnixStartDate & "&period2=" & UnixEndDate & "&interval=1d&events=history&crumb=" & crumb

    http.Open "GET", url, False
    http.setRequestHeader "Cookie", cookie
    http.send

    YahooRequest = http.responseText
End Function

答案 14 :(得分:2)

对于那些Excel / VBA用户,我使用上述建议开发了一个VBA方法,以从更新的Yahoo网站中提取历史价格。下面列出了关键代码段,我还提供了测试工作簿。

首先要求在尝试从Yahoo提取数据之前获取Crumb和Cookie值的设置..

Dim strUrl                      As String: strUrl = "https://finance.yahoo.com/lookup?s=%7B0%7D"    'Symbol lookup used to set the values
Dim objRequest                  As WinHTTP.WinHttpRequest

Set objRequest = New WinHttp.WinHttpRequest

With objRequest
    .Open "GET", strUrl, True
    .setRequestHeader "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"
    .send
    .waitForResponse
    strCrumb = strExtractCrumb(.responseText)
    strCookie = Split(.getResponseHeader("Set-Cookie"), ";")(0)
End With

请参阅我的网站的以下Yahoo Historical Price Extract链接以获取示例文件以及我用于从Yahoo网站提取历史安全价格的方法的更多详细信息

答案 15 :(得分:1)

到目前为止提到的那种方法(雅虎,谷歌和Intrinio)的另一种方法是免费获取Alpha Vantage的历史数据。他们的网络服务提供日内,每日,调整后的股票价格和50多项技术指标。他们甚至可以通过Deriscope直接发送到Excel - 也是免费的。 (我是后者的作者。)

答案 16 :(得分:1)

的Javascript

查找cookie;

match = document.cookie.match(new RegExp('B=([^;]+)'));
alert (match[1]);

找到面包屑;

i=document.body.innerHTML.search("CrumbStore")
if (i>=0) alert (document.body.innerHTML.substr(i+22,11))

查找移动设备的碎屑;

i=document.body.innerHTML.search('USER={\"crumb\":'); 
if (i>=0) alert(document.body.innerHTML.substr(i+15,11));

并且可能最好等待页面(例如https://finance.yahoo.com/quote/goog)先加载,你可以 检查一下;

document.readyState

答案 17 :(得分:1)

为什么不使用提供完全访问权限的现成版本。没有故障:

tickers='AAPL' 

from pandas_datareader import data as wb

new_data = pd.DataFrame()
for t in tickers :

    new_data[t] = wb.DataReader(t, data_source ='yahoo', start = '2004-1-1')['Adj Close']

a = new_data[t]

答案 18 :(得分:1)

你实际上并不需要做2个获取雅虎数据的请求。我使用此链接https://ca.finance.yahoo.com/quote/AAAP/history?period1=1474000669&period2=1505536669&interval=1d&filter=history&frequency=1d

你可以从中获取cookie,但它包含了JSON格式的历史报价数据。下载页面后,我将Json数据从中删除。保存网址请求。

答案 19 :(得分:1)

我在同一条船上。我设法从雅虎下载了一些vb.net frankencode,这些代码是我用谷歌,SOF和一些令人头疼的东西制作而成的。

然而,我发现了Intrinio(查找),注册了,我的免费帐户每天为我提供500个历史数据api调用,拥有更多数据并且比雅虎准确得多。我重写了我的Intrinio API代码,我很高兴作为一个蛤蜊​​。

顺便说一句,我不工作或与Intrinio有任何关系,但是他们节省了我的屁股时间......

答案 20 :(得分:1)

我发现有一个修复工作正常。请看我的帖子:

Yahoo Finance API / URL not working: Python fix for Pandas DataReader我按照https://pypi.python.org/pypi/fix-yahoo-finance中的步骤执行:$ pip install fix_yahoo_finance --upgrade --no-cache-dir(并且还升级了pandas_datareader以确定)并且测试正常:

from pandas_datareader import data as pdr
import fix_yahoo_finance

data = pdr.get_data_yahoo('BHP.AX', start='2017-04-23', end='2017-05-24')

另请注意,最后2个数据列的顺序是“Adj Close”和“Volume”,所以出于我的目的,我已将列重置为原始顺序:

cols = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close']
data = data.reindex(columns=cols)

答案 21 :(得分:0)

可以从documentation获取当前和历史数据。对我来说非常好。

答案 22 :(得分:0)

对于Python 3,用户更改为

URL = 'https://query1.finance.yahoo.com/v7/finance/download/AAAP?period1=1494605670&period2=1495815270&interval=1d&events=history&crumb=IJ.ilcJlkrZ'

来自

URL = 'https://chartapi.finance.yahoo.com/instrument/1.0/AAAP/chartdata;type=quote;range=10d/csv/'

response = request.urlopen(url) 至 response = requests.get(url,cookies = {'B':cookie}) response.text中的数据

数据格式完全不同,但至少它现在正常工作

答案 23 :(得分:0)

我结合了上述处理crumb / cookie刷新的一些想法,特别是来自@Dennis,并创建了一个可以这样调用的vb.net类:

Imports System.Net
Imports System.Net.Http
Imports System.Text.RegularExpressions

Namespace YahooFinance
    Public Class YahooHistoryPrice

        Public Property [Date] As DateTime

        Public Property Open As Double

        Public Property High As Double

        Public Property Low As Double

        Public Property Close As Double

        Public Property Volume As Double

        Public Property AdjClose As Double
    End Class

    Public Class YahooFinanceFactory
        Public Property Cookie As String
        Public Property Crumb As String
        Public Property CrumbUrl As String = "https://finance.yahoo.com/quote/{0}?p={0}"
        Public Property DownloadUrl As String = "https://query1.finance.yahoo.com/v7/finance/download/{0}?period1={1}&period2={2}&interval=1d&events={3}&crumb={4}"

        Public Property Timeout As Integer = 5
        Public Property NoRefreshRetries As Integer = 10
        Public Property NoDownloadRetries As Integer = 10
        Private Property Regex_crumb As Regex

        Public Shared Async Function CreateAsync(Optional noRefreshRetries As Integer = 10, Optional noDownloadRetries As Integer = 10, Optional timeout As Integer = 5, Optional crumbUrl As String = "https://finance.yahoo.com/quote/{0}?p={0}", Optional downloadUrl As String = "https://query1.finance.yahoo.com/v7/finance/download/{0}?period1={1}&period2={2}&interval=1d&events={3}&crumb={4}") As Task(Of YahooFinanceFactory)
            Return Await (New YahooFinanceFactory With {
                .NoRefreshRetries = noRefreshRetries,
                .NoDownloadRetries = noDownloadRetries,
                .Timeout = timeout,
                .CrumbUrl = crumbUrl,
                .DownloadUrl = downloadUrl
            }).RefreshAsync()
        End Function

        Public Async Function GetHistoricalDataAsync(symbol As String, dateFrom As Date) As Task(Of IEnumerable(Of YahooHistoryPrice))
            Dim count As Integer = 0

            If Not IsValid Then
                Throw New Exception("Invalid YahooFinanceFactory instance")
            End If

            Dim csvData = Await GetRawAsync(symbol, dateFrom, Now).ConfigureAwait(False)

            If csvData IsNot Nothing Then
                Return ParsePrice(csvData)
            End If

            Return Array.Empty(Of YahooHistoryPrice)
        End Function

        Public Async Function GetRawAsync(symbol As String, start As DateTime, [end] As DateTime) As Task(Of String)
            Dim count = 0

            While count < NoDownloadRetries
                Try
                    Dim cookies = New CookieContainer
                    cookies.Add(New Cookie("B", If(Cookie.StartsWith("B="), Cookie.Substring(2), Cookie), "/", ".yahoo.com"))

                    Using handler = New HttpClientHandler With {.CookieContainer = cookies}
                        Using client = New HttpClient(handler) With {.Timeout = TimeSpan.FromSeconds(Timeout)}
                            Dim httpResponse = Await client.GetAsync(GetDownloadUrl(symbol, start)).ConfigureAwait(False)
                            Return Await httpResponse.Content.ReadAsStringAsync
                        End Using
                    End Using
                Catch ex As Exception
                    If count >= NoDownloadRetries - 1 Then
                        Throw
                    End If
                End Try

                count += 1
            End While

            Throw New Exception("Retries exhausted")
        End Function

        Private Function ParsePrice(ByVal csvData As String) As IEnumerable(Of YahooHistoryPrice)
            Dim lst = New List(Of YahooHistoryPrice)
            Dim rows = csvData.Split(Convert.ToChar(10))
            For i = 1 To rows.Length - 1
                Dim row = rows(i)
                If String.IsNullOrEmpty(row) Then
                    Continue For
                End If
                Dim cols = row.Split(","c)
                If cols(1) = "null" Then
                    Continue For
                End If
                Dim itm = New YahooHistoryPrice With {.Date = DateTime.Parse(cols(0)), .Open = Convert.ToDouble(cols(1)), .High = Convert.ToDouble(cols(2)), .Low = Convert.ToDouble(cols(3)), .Close = Convert.ToDouble(cols(4)), .AdjClose = Convert.ToDouble(cols(5))}
                If cols(6) <> "null" Then
                    itm.Volume = Convert.ToDouble(cols(6))
                End If
                lst.Add(itm)
            Next

            Return lst
        End Function

        Public ReadOnly Property IsValid() As Boolean
            Get
                Return Not String.IsNullOrWhiteSpace(Cookie) And Not String.IsNullOrWhiteSpace(Crumb)
            End Get
        End Property

        Public Function GetDownloadUrl(symbol As String, dateFrom As Date, Optional eventType As String = "history") As String
            Return String.Format(DownloadUrl, symbol, Math.Round(DateTimeToUnixTimestamp(dateFrom), 0), Math.Round(DateTimeToUnixTimestamp(Now.AddDays(-1)), 0), eventType, Crumb)
        End Function

        Public Function GetCrumbUrl(symbol As String) As String
            Return String.Format(Me.CrumbUrl, symbol)
        End Function

        Public Function DateTimeToUnixTimestamp(dateTime As DateTime) As Double
            Return (dateTime.ToUniversalTime() - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds
        End Function

        Private Async Function RefreshAsync(Optional symbol As String = "SPY") As Task(Of YahooFinanceFactory)
            Dim count = 0

            While count < NoRefreshRetries And Not IsValid
                Try
                    Using client = New HttpClient With {.Timeout = TimeSpan.FromSeconds(Timeout)}
                        Dim httpResponse = Await client.GetAsync(GetCrumbUrl(symbol)).ConfigureAwait(False)
                        Me.Cookie = httpResponse.Headers.First(Function(f) f.Key = "Set-Cookie").Value.FirstOrDefault?.Split(";"c)(0)
                        Dim html = Await httpResponse.Content.ReadAsStringAsync
                        Me.Crumb = GetCrumb(html)
                        If Crumb IsNot Nothing Then
                            Return Me
                        End If
                    End Using
                Catch ex As Exception
                    If count >= NoRefreshRetries - 1 Then
                        Cookie = ""
                        Crumb = ""
                        Throw
                    End If
                End Try

                count += 1
            End While

            Cookie = ""
            Crumb = ""
            Throw New Exception("Could not refresh YahooFinanceFactory")
        End Function

        Private Function GetCrumb(html As String) As String
            Dim crumb As String = Nothing

            If Regex_crumb Is Nothing Then
                Regex_crumb = New Regex("CrumbStore"":{""crumb"":""(?<crumb>.+?)""}", RegexOptions.CultureInvariant Or RegexOptions.Compiled, TimeSpan.FromSeconds(5))
            End If

            Dim matches As MatchCollection = Regex_crumb.Matches(html)
            If matches.Count > 0 Then
                crumb = matches(0).Groups("crumb").Value
                crumb = System.Text.RegularExpressions.Regex.Unescape(crumb)
            Else
                Throw New Exception("Regex no match")
            End If

            Return crumb
        End Function
    End Class
End Namespace

班级本身就在这里:

Gradle sync failed: Uninitialized object exists on backward branch 70 Exception Details: Location: 
com/android/build/gradle/tasks/BuildArtifactReportTask.newArtifact(Lcom/android/build/api/artifact/BuildableArtifact;)
Lcom/android/build/gradle/tasks/BuildArtifactReportTask$BuildableArtifactData;

答案 24 :(得分:0)

如果您尝试将yahooFinance api与Java连接。只需添加以下依赖项即可。

<dependency>
    <groupId>com.yahoofinance-api</groupId>
    <artifactId>YahooFinanceAPI</artifactId>
    <version>3.13.0</version>
</dependency>