欢迎来到Python for Finance教程系列的第7部分。 在之前的教程中,我们为整个标准普尔500强公司抓取了雅虎财经数据。 在本教程中,我们将把这些数据组合到一个DataFrame中。

到此为止的代码:

import bs4 as bs
import datetime as dt
import os
import pandas_datareader.data as web
import pickle
import requests def save_sp500_tickers():
resp = requests.get('http://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
soup = bs.BeautifulSoup(resp.text, 'lxml')
table = soup.find('table', {'class': 'wikitable sortable'})
tickers = []
for row in table.findAll('tr')[1:]:
ticker = row.findAll('td')[0].text
tickers.append(ticker)
with open("sp500tickers.pickle", "wb") as f:
pickle.dump(tickers, f)
return tickers # save_sp500_tickers()
def get_data_from_yahoo(reload_sp500=False):
if reload_sp500:
tickers = save_sp500_tickers()
else:
with open("sp500tickers.pickle", "rb") as f:
tickers = pickle.load(f)
if not os.path.exists('stock_dfs'):
os.makedirs('stock_dfs') start = dt.datetime(2010, 1, 1)
end = dt.datetime.now()
for ticker in tickers:
# just in case your connection breaks, we'd like to save our progress!
if not os.path.exists('stock_dfs/{}.csv'.format(ticker)):
df = web.DataReader(ticker, 'morningstar', start, end)
df.reset_index(inplace=True)
df.set_index("Date", inplace=True)
df = df.drop("Symbol", axis=1)
df.to_csv('stock_dfs/{}.csv'.format(ticker))
else:
print('Already have {}'.format(ticker)) get_data_from_yahoo()

尽管我们掌握了所有数据,但我们可能想要一起评估数据。为此,我们将把所有的股票数据集合在一起。目前的每个股票文件都有:开盘价,最高价,最低价,收盘价,成交量和调整收盘价。至少要开始,我们现在大多只对调整后的收盘感兴趣。

def compile_data():
with open("sp500tickers.pickle","rb") as f:
tickers = pickle.load(f) main_df = pd.DataFrame()

首先,我们拉取我们之前制作的代码列表,并从一个名为main_df的空数据框开始。现在,我们准备读取每个股票的数据集合:

    for count,ticker in enumerate(tickers):
df = pd.read_csv('stock_dfs/{}.csv'.format(ticker))
df.set_index('Date', inplace=True)

你不需要在这里使用Python的枚举,我只是使用它,所以我们知道我们在读取所有数据的过程中。你可以迭代代码。从这一点,我们*可以*生成有趣数据的额外列,如:

        df ['{} _ HL_pct_diff'.format(ticker)] =(df ['High'] - df ['Low'])/ df ['Low']
df ['{} _ daily_pct_chng'.format(ticker)] =(df ['Close'] - df ['Open'])/ df ['Open']

但现在,我们不会因此而烦恼。只要知道这可能是一条追寻道路的道路。相反,我们真的只是对Adj Adj列感兴趣:

        df.rename(columns={'Adj Close':ticker}, inplace=True)
df.drop(['Open','High','Low','Close','Volume'],1,inplace=True)

现在我们已经有了这个专栏(或者像上面那样额外的......但是请记住,在这个例子中,我们没有做HL_pct_diff或daily_pct_chng)。请注意,我们已将Adj Adj列重命名为任何股票代码名称。我们开始构建共享数据框:

        if main_df.empty:
main_df = df
else:
main_df = main_df.join(df, how='outer')

如果main_df中没有任何内容,那么我们将从当前的df开始,否则我们将使用Pandas的加入。

仍然在这个for循环中,我们将再添加两行:

        if count % 10 == 0:
print(count)

这将只输出当前股票的数量,如果它可以被10整除。什么样的计数%10给我们的是余数,如果计数除以10.因此,如果我们问如果计数%10 == 0,我们是 只有看到if语句,如果当前计数除以10,余数为0,或者如果它完全可以被10整除,那么才会出现True。

当我们完成for循环时:

    print(main_df.head())
main_df.to_csv('sp500_joined_closes.csv')

这个函数调用它到这一点:

    with open("sp500tickers.pickle","rb") as f:
tickers = pickle.load(f) main_df = pd.DataFrame() for count,ticker in enumerate(tickers):
df = pd.read_csv('stock_dfs/{}.csv'.format(ticker))
df.set_index('Date', inplace=True) df.rename(columns={'Adj Close':ticker}, inplace=True)
df.drop(['Open','High','Low','Close','Volume'],1,inplace=True) if main_df.empty:
main_df = df
else:
main_df = main_df.join(df, how='outer') if count % 10 == 0:
print(count)
print(main_df.head())
main_df.to_csv('sp500_joined_closes.csv') compile_data()

当前完整的代码为:

import bs4 as bs
import datetime as dt
import os
import pandas as pd
import pandas_datareader.data as web
import pickle
import requests def save_sp500_tickers():
resp = requests.get('http://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
soup = bs.BeautifulSoup(resp.text, 'lxml')
table = soup.find('table', {'class': 'wikitable sortable'})
tickers = []
for row in table.findAll('tr')[1:]:
ticker = row.findAll('td')[0].text
tickers.append(ticker)
with open("sp500tickers.pickle", "wb") as f:
pickle.dump(tickers, f)
return tickers # save_sp500_tickers()
def get_data_from_yahoo(reload_sp500=False):
if reload_sp500:
tickers = save_sp500_tickers()
else:
with open("sp500tickers.pickle", "rb") as f:
tickers = pickle.load(f)
if not os.path.exists('stock_dfs'):
os.makedirs('stock_dfs') start = dt.datetime(2010, 1, 1)
end = dt.datetime.now()
for ticker in tickers:
# just in case your connection breaks, we'd like to save our progress!
if not os.path.exists('stock_dfs/{}.csv'.format(ticker)):
df = web.DataReader(ticker, 'morningstar', start, end)
df.reset_index(inplace=True)
df.set_index("Date", inplace=True)
df = df.drop("Symbol", axis=1)
df.to_csv('stock_dfs/{}.csv'.format(ticker))
else:
print('Already have {}'.format(ticker)) def compile_data():
with open("sp500tickers.pickle", "rb") as f:
tickers = pickle.load(f) main_df = pd.DataFrame() for count, ticker in enumerate(tickers):
df = pd.read_csv('stock_dfs/{}.csv'.format(ticker))
df.set_index('Date', inplace=True) df.rename(columns={'Adj Close': ticker}, inplace=True)
df.drop(['Open', 'High', 'Low', 'Close', 'Volume'], 1, inplace=True) if main_df.empty:
main_df = df
else:
main_df = main_df.join(df, how='outer') if count % 10 == 0:
print(count)
print(main_df.head())
main_df.to_csv('sp500_joined_closes.csv') compile_data()

在下一个教程中,我们将试图查看我们是否能够快速找到数据中的任何关系。

Python股票分析系列——数据整合.p7的更多相关文章

  1. Python股票分析系列——数据整理和绘制.p2

    该系列视频已经搬运至bilibili: 点击查看 欢迎来到Python for Finance教程系列的第2部分. 在本教程中,我们将利用我们的股票数据进一步分解一些基本的数据操作和可视化. 我们将要 ...

  2. Python股票分析系列——系列介绍和获取股票数据.p1

    本系列转载自youtuber sentdex博主的教程视频内容 https://www.youtube.com/watch?v=19yyasfGLhk&index=4&list=PLQ ...

  3. Python股票分析系列——基础股票数据操作(二).p4

    该系列视频已经搬运至bilibili: 点击查看 欢迎来到Python for Finance教程系列的第4部分.在本教程中,我们将基于Adj Close列创建烛台/ OHLC图,这将允许我介绍重新采 ...

  4. Python股票分析系列——基础股票数据操作(一).p3

    该系列视频已经搬运至bilibili: 点击查看 欢迎来到Python for Finance教程系列的第3部分.在本教程中,我们将使用我们的股票数据进一步分解一些基本的数据操作和可视化.我们将要使用 ...

  5. Python股票分析系列——自动获取标普500股票列表.p5

    该系列视频已经搬运至bilibili: 点击查看 欢迎来到Python for Finance教程系列的第5部分.在本教程和接下来的几节中,我们将着手研究如何为更多公司提供大量的定价信息,以及如何一次 ...

  6. Python股票分析系列——获得标普500的所有公司股票数据.p6

    该系列视频已经搬运至bilibili: 点击查看 欢迎来到Python for Finance教程系列的第6部分. 在之前的Python教程中,我们介绍了如何获取我们感兴趣的公司名单(在我们的案例中是 ...

  7. python量化分析系列之---5行代码实现1秒内获取一次所有股票的实时分笔数据

    python量化分析系列之---5行代码实现1秒内获取一次所有股票的实时分笔数据 最近工作太忙了,有一个星期没有更新文章了,本来这一期打算分享一些对龙虎榜数据的分析结果的,现在还没有把数据内的价值很好 ...

  8. 金融量化分析-python量化分析系列之---使用python获取股票历史数据和实时分笔数据

    财经数据接口包tushare的使用(一) Tushare是一款开源免费的金融数据接口包,可以用于获取股票的历史数据.年度季度报表数据.实时分笔数据.历史分笔数据,本文对tushare的用法,已经存在的 ...

  9. python提取分析表格数据

    #/bin/python3.4# -*- coding: utf-8 -*- import xlrd def open_excel(file="file.xls"): try: d ...

随机推荐

  1. Spark之UDF

    package big.data.analyse.udfudaf import org.apache.spark.sql.types.{IntegerType, StringType, StructF ...

  2. [20181226]简单探究cluster table.txt

    [20181226]简单探究cluster table.txt --//简单探究cluster table.以前也做过,有点生疏了. 1.环境:SCOTT@book> @ ver1PORT_ST ...

  3. C#核心基础--浅谈类和对象的概念

    浅谈类和对象的概念 一.什么是类?什么是对象? 学习一门面向对象编程语言,我们必须得知道什么是类?什么是对象? 类(Class)实际上是对某种类型的对象定义变量和方法的原型.它表示对现实生活中一类具有 ...

  4. SQL WHERE 子句

    WHERE 子句 如需有条件地从表中选取数据,可将 WHERE 子句添加到 SELECT 语句. 语法 SELECT 列名称 FROM 表名称 WHERE 列 运算符 值 释意:选取 [列] 来自 [ ...

  5. EOS开发语言和石墨烯技术介绍

    EOS 的智能合约基于 WebAssembly(WASM) 技术执行用户生成的应用程序和代码.WASM是一项新兴的网络标准,得到了谷歌,微软,苹果等公司的广泛支持.目前,用于构建编译为WASM的应用程 ...

  6. [Hive_add_9] Hive 的存储格式

    0. 说明 Hive 的存储格式 | textfile | sequencefile | rcfile | orc | parquet | 1. Hive的存储格式 1.1 textfile 行式存储 ...

  7. python拟合数据,并通过拟合的曲线去预测新值的方法

    from scipy import interpolate import matplotlib.pyplot as plt import numpy as np def f(x): x_points ...

  8. python——函数之装饰器

    1 问题 实际生活中,我们很难一次性就把一个函数代码写得完美无缺.当我们需要对以前的函数添加新功能时,我们应该怎么做? 2 问题解决思路 (1)可以直接修改原来的函数,在函数内直接修改.当我们对多个函 ...

  9. June 3. 2018 Week 23rd Sunday

    You only get one shot; do not miss your chance to blow. 机会只有一次,不要错过. From Eminem, "Lose Yoursel ...

  10. aliyun mysql

    https://segmentfault.com/q/1010000009603559?sort=created