▌前言
上一个视频介绍了如何从quandl里获取单一股票数据,本视频将讲解如何从quandl中获取大量的股票数据。
▌视频
▌视频出处
视频系列:Scikit-learn Machine Learning with Python and SKlearn
本视频出处:Scikit Learn Machine Learning for investing Tutorial with Python p. 17
哔哩哔哩:Scikit Learn Machine Learning for investing Tutorial with Python p. 17
▌内容
首先,我们自定义一个function def Stock_Prices()
,然后读取本地文件夹_KeyStats
中的文件,这个跟之前教程读取文件的原理一样:
def Stock_Prices():
df = pd.DataFrame()
statspath = path + '/_KeyStats'
stock_list = [x[0] for x in os.walk(statspath)]
得到股票代码列表后,我们用for 来遍历每一只股票的代码,然后通过quandl来获取其数据:
def Stock_Prices():
df = pd.DataFrame()
statspath = path + '/_KeyStats'
stock_list = [x[0] for x in os.walk(statspath)]
for each_dir in stock_list[1:]:
ticker = each_dir.split("\\")[1]
print(ticker)
#股票代码都是大写的,所以用到Upper()
name = 'WIKI/'+ticker.upper()
#从quandl获取股票数据
data = quandl.get(name
,trim_start = "2000-12-12",
trim_end = "2014-12-30",
authtoken=auth_tok)
#建立以[ticker.upper()]为名称的列,然后只获取`Adj. Close`的数据。
data[ticker.upper()] = data['Adj. Close']
#合并新的列表
df = pd.concat([df, data[ticker.upper()]], axis = 1)
最后,为了防止获取股票数据时出现网络错误等问题,我们加入了try - except
。
▌结果
▌源代码
import pandas as pd
import os
import quandl
import time
# auth_tok = "api key 代码"
auth_tok = open("quandl_auth_tok.txt","r").read()
path = '../intraQuarter'
def Stock_Prices():
df = pd.DataFrame()
statspath = path + '/_KeyStats'
stock_list = [x[0] for x in os.walk(statspath)]
for each_dir in stock_list[1:]:
try:
ticker = each_dir.split("\\")[1]
print(ticker)
#股票代码都是大写的,所以用到Upper()
name = 'WIKI/'+ticker.upper()
#从quandl获取股票数据
data = quandl.get(name
,trim_start = "2000-12-12",
trim_end = "2014-12-30",
authtoken=auth_tok)
data[ticker.upper()] = data['Adj. Close']
df = pd.concat([df, data[ticker.upper()]], axis = 1)
except Exception as e:
print(e)
#如果出现获取错误,等待10秒后继续执行代码
time.sleep(10)
try:
ticker = each_dir.split("\\")[1]
print(ticker)
name = 'WIKI/'+ticker.upper()
data = quandl.get(name
,trim_start = "2000-12-12",
trim_end = "2014-12-30",
authtoken=auth_tok)
#建立以[ticker.upper()]为名称的列,然后只获取`Adj. Close`的数据。
data[ticker.upper()] = data['Adj. Close']
df = pd.concat([df, data[ticker.upper()]], axis = 1)
except Exception as e:
print(e)
df.to_csv('stock_prices.csv')
Stock_Prices()
▌最后
虽然分c君_BingWong
只是作为一名搬运工,连码农都称不上。 但制作代码中的注释、翻译和搬运都花了很多时间,请各位大侠高抬贵手,在转载时请注明出处。