Download history stock prices automatically from yahoo finance in python

后端 未结 6 1881
忘掉有多难
忘掉有多难 2020-12-04 05:42

Is there a way to automatically download historical prices of stocks from yahoo finance or google finance (csv format)? Preferably in Python.

6条回答
  •  感情败类
    2020-12-04 05:59

    Extending @Def_Os's answer with an actual demo...

    As @Def_Os has already said - using Pandas Datareader makes this task a real fun

    In [12]: from pandas_datareader import data
    

    pulling all available historical data for AAPL starting from 1980-01-01

    #In [13]: aapl = data.DataReader('AAPL', 'yahoo', '1980-01-01')
    
    # yahoo api is inconsistent for getting historical data, please use google instead.
    In [13]: aapl = data.DataReader('AAPL', 'google', '1980-01-01')
    

    first 5 rows

    In [14]: aapl.head()
    Out[14]:
                     Open       High     Low   Close     Volume  Adj Close
    Date
    1980-12-12  28.750000  28.875000  28.750  28.750  117258400   0.431358
    1980-12-15  27.375001  27.375001  27.250  27.250   43971200   0.408852
    1980-12-16  25.375000  25.375000  25.250  25.250   26432000   0.378845
    1980-12-17  25.875000  25.999999  25.875  25.875   21610400   0.388222
    1980-12-18  26.625000  26.750000  26.625  26.625   18362400   0.399475
    

    last 5 rows

    In [15]: aapl.tail()
    Out[15]:
                     Open       High        Low      Close    Volume  Adj Close
    Date
    2016-06-07  99.250000  99.870003  98.959999  99.029999  22366400  99.029999
    2016-06-08  99.019997  99.559998  98.680000  98.940002  20812700  98.940002
    2016-06-09  98.500000  99.989998  98.459999  99.650002  26419600  99.650002
    2016-06-10  98.529999  99.349998  98.480003  98.830002  31462100  98.830002
    2016-06-13  98.690002  99.120003  97.099998  97.339996  37612900  97.339996
    

    save all data as CSV file

    In [16]: aapl.to_csv('d:/temp/aapl_data.csv')
    

    d:/temp/aapl_data.csv - 5 first rows

    Date,Open,High,Low,Close,Volume,Adj Close
    1980-12-12,28.75,28.875,28.75,28.75,117258400,0.431358
    1980-12-15,27.375001,27.375001,27.25,27.25,43971200,0.408852
    1980-12-16,25.375,25.375,25.25,25.25,26432000,0.378845
    1980-12-17,25.875,25.999999,25.875,25.875,21610400,0.38822199999999996
    1980-12-18,26.625,26.75,26.625,26.625,18362400,0.399475
    ...
    

提交回复
热议问题