下载历史股票指数数据

时间:2017-07-01 08:50:08

标签: python

我有来自Google财经here的股票指数(NSE:NIFTY50)的以下数据。我想将上述数据下载为csv,以便我可以对其进行一些分析。我该如何下载?如果可以,我宁愿使用python。

1 个答案:

答案 0 :(得分:1)

您应该可以使用以下代码下载库存数据。

import requests
from bs4 import BeautifulSoup
import pandas as pd 

url = "https://www.google.com/finance/historical?cid=207437&startdate=Jan%201%2C%201971&enddate=Jul%201%2C%202017&start={0}&num=30"
#change this to 138
how_many_pages=3
start=0

for i in range(how_many_pages):
    new_url = url.format(start)
    page = requests.get(new_url)
    soup = BeautifulSoup(page.content, "html5lib")
    table = soup.find_all('table', class_='gf-table historical_price')[0] 

    columns_header = [th.getText() for th in table.findAll('tr')[0].findAll('th')]
    data_rows=table.findAll('tr')[1:]
    data=[[td.getText() for td in data_rows[i].findAll(['td'])] for i in range(len(data_rows))]

    if (start == 0):
        final_df = pd.DataFrame(data, columns=columns_header)
    else:
        df=pd.DataFrame(data, columns=columns_header)
        final_df = pd.concat([final_df, df],axis=0)
    start += 30
#write your code to save final_df to csv

如果有帮助,请不要忘记标记答案:)