两周前我刚开始使用python,并研究了从Tiingo获取股票数据的代码。我设法通过运行以下代码获得了我需要的所有数据。但是,我似乎无法在 excel 的输出中包含实际的股票"股票代码"。有人知道为什么吗?感谢所有帮助!
谢谢!
import datetime as dt
import pandas as pd
from pandas import DataFrame
import numpy as np
import os # creates new directories
import matplotlib.pyplot as plt
from matplotlib import style
import pandas_datareader.data as web
import pandas_datareader as pdr
from scipy import stats
import bs4 as bs
import pickle
import requests
import lxml
import win32com.client as win32
import xlsxwriter
tiingo_api_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx' #'YOUR API KEY'
tickers=[ 'EWA', 'EWO', 'EWK', 'EWC']
i = 0
h = 0
year = 252 # trading days
month = year/12
years = 5
dtToDate = str(dt.datetime.now().date())
print(type(dtToDate))
dtFromDate = '2014-01-01'
print("Start Date: " + dtFromDate)
print("End Date: " + dtToDate)
def get_data_from_tiingoMarketsDaily():
dfPriceDataday = pd.DataFrame()
for ticker in tickers:
print('Processing Stock Data for: ' + ticker)
request_url = "https://api.tiingo.com/tiingo/daily/"+ticker+"/prices?startDate="+str(dtFromDate)+"&endDate="+str(dtToDate)+"&token="+tiingo_api_key
data = pd.read_json(request_url)[['date', 'adjOpen', 'adjHigh', 'adjLow', 'adjClose', 'volume']]
data['date'] = pd.to_datetime(data['date']).dt.strftime("%d/%m/%Y")
data.rename(columns={ 'date': 'Date', 'adjOpen': 'AdjOpen', 'adjHigh': 'AdjHigh', 'adjLow': 'AdjLow', 'adjClose': 'AdjClose', 'volume': 'Volume'}, inplace=True)
data.sort_index(ascending=False, inplace=True)
dfPriceDataday = dfPriceDataday.append(data)
writer = pd.ExcelWriter("StockData.xlsx", engine='xlsxwriter')
dfPriceDataday.to_excel(writer,sheet_name='Daily',index=False)
writer.save()
get_data_from_tiingoMarketsDaily()
我不确定 Tiingo 如何返回数据,但您可以通过将 Ticker 列添加到 Excel 文件来解决此问题。做出这样的改变
for ticker in tickers:
print('Processing Stock Data for: ' + ticker)
request_url = "https://api.tiingo.com/tiingo/daily/"+ticker+"/prices?startDate="+str(dtFromDate)+"&endDate="+str(dtToDate)+"&token="+tiingo_api_key
data = pd.read_json(request_url)[['date', 'adjOpen', 'adjHigh', 'adjLow', 'adjClose', 'volume']]
data['date'] = pd.to_datetime(data['date']).dt.strftime("%d/%m/%Y")
data.rename(columns={ 'date': 'Date', 'adjOpen': 'AdjOpen', 'adjHigh': 'AdjHigh', 'adjLow': 'AdjLow', 'adjClose': 'AdjClose', 'volume': 'Volume'}, inplace=True)
data['Ticker'] = str(ticker)
data.sort_index(ascending=False, inplace=True)
dfPriceDataday = dfPriceDataday.append(data)
希望这就是你要找的。