1.获取数据:

想要获得道指30只成分股的最新股价

import requests
import re
import pandas as pddef retrieve_dji_list():try:r = requests.get('https://money.cnn.com/data/dow30/')except ConnectionError as err:print(err)search_pattern = re.compile('class="wsod_symbol">(.*?)<\/a>.*?<span.*?">(.*?)<\/span>.*?\n.*?class="wsod_stream">(.*?)<\/span>')dji_list_in_text = re.findall(search_pattern, r.text)dji_list = []for item in dji_list_in_text:dji_list.append([item[0], item[1], float(item[2])])return dji_listdji_list = retrieve_dji_list()
djidf = pd.DataFrame(dji_list)
print(djidf)

整理数据, 改变列名, index等

cols=['code','name','lasttrade']
djidf.columns=cols # 改变列名
djidf.index=range(1,len(djidf)+1)

最后结果为:

数据的选择

djidf.code   # 获取code列+index
djidf['code']  # 获取code列 , 两者同功能
djidf.loc[1:5,]  # 前5行
djidf.loc[:,['code','lasttrade']] #所有行
djidf.loc[1:5,['code','lasttrade']] #1-5行, loc表示标签index
djidf.loc[1,['code','lasttrade']] #1行
djidf.at[1,'lasttrade']  # 只有一个值的时候可以用at
djidf.iloc[2:4,[0,2]]  # 表示物理文职, 并且4取不到, 就只有第三行第四行
djidf.iat[1,2]  # 单个值

简单的数据筛选: 平均股价, 股价大于180的公司名

djidf.lasttrade.mean()  # 121.132
djidf[djidf.lasttrade>=180].name

找到股价前三名的公司 , 降序排列

tempdf=djidf.sort_values(by='lasttrade',ascending=False)
tempdf[:3].name

如何根据index排序呢? 专门有函数sort_index()

df=pd.DataFrame(np.random.randn(3,3),index=['c','b','a'],columns=list('xyz'))
df.sort_index()  # 根据index 进行排序

*获取AXP公司过去一年的股价数据获取

import requests
import re
import json
import pandas as pd
from datetime import  date
def retrieve_quotes_historical(stock_code):quotes = []url = 'https://finance.yahoo.com/quote/%s/history?p=%s' % (stock_code, stock_code)try:r = requests.get(url)except ConnectionError as err:print(err)m = re.findall('"HistoricalPriceStore":{"prices":(.*?),"isPending"', r.text)if m:quotes = json.loads(m[0])       # m = ['[{...},{...},...]']quotes = quotes[::-1]         # 原先数据为date最新的在最前面return  [item for item in quotes if not 'type' in item]
quotes = retrieve_quotes_historical('AXP')
list1=[]
for i in range(len(quotes)):x=date.fromtimestamp(quotes[i]['date'])y=date.strftime(x,'%Y-%m-%d')list1.append(y)
quotesdf_ori=pd.DataFrame(quotes,index=list1)
quotesdf_m = quotesdf_ori.drop(['adjclose'], axis = 1)  #删除adjclose列
quotesdf=quotesdf_m.drop(['date'],axis=1)
print(quotesdf)

上述需要对时间进行处理, 将时间转为’%Y-%m-%d’的格式, 并且将这个时间作为一个list 成为quotesdf的index.

数据的筛选

quotesdf[(quotesdf.index>='2017-03-01') & (quotesdf.index<='2017-03-31')]
quotesdf[(quotesdf.index>='2017-11-30') & (quotesdf.index<='2018-03-31')&
(quotesdf.close>=90)]

简单计算

(1) 统计AXP股价涨跌的天数 (close>open)

len(quotesdf.close>quotesdf.open)

(2) 相邻两天的涨跌

import numpy as np
status=np.sign(np.diff(quotesdf.close))
status  # 250 的长度, 比quotesdf 少1
status[np.where(status==1)].size  # np.where(status==1)是由下标构成的array
#

上述统计还可以直接用describe函数, 得到基本统计信息

import pandas as pd
import numpy as np
index_df = pd.DataFrame(np.random.rand(3,3), index=['a','b','c'], columns=['index_1','index_2','index_3'])
index_df.describe() # 超级强大

(3) 统计2018一月的交易日天数

t=quotesdf[(quotesdf.index>='2018-01-01') & (quotesdf.index<'2018-02-01')]
len(t)  #21

进一步, 如何统计近一年每个月的交易日天数?

统计每个月的出现天数就行了, 如何提取月份信息? 要把时间的字符串转化为 时间格式,

import time
list2=[]
for i in range(len(quotesdf)):temp=time.strptime(quotesdf.index[i],'%Y-%m-%d')list2.append(temp.tm_mon)  # 取月份
tempdf=quotesdf.copy()
tempdf['month']=list2  # 新增一列月份的数据
print(tempdf['month'].value_counts())  # 计算每个月的出现次数

注意:

strptime 将字符串格式化为time结构, time 中会包含年份, 月份等信息
strftime 将time 结构格式化一个字符串, 之前生成quotesdf中用到过

上述方法略微麻烦, 如何快速知道每个月的交易日天数? groupby

# 统计每一月的股票开盘天数
x=tempdf.groupby('month').count()
# 统计近一年每个月的成交量
tempdf.groupby('month').sum().volume
# 先每个月进行求和, 但是这些对其他列也进行了求和, 属于无效计算, 如何避免?
tempdf.groupby('month').volume.sum()  # 交换顺序即可

引申: 一般groupby 与apply 在一起用. 具体不展开了

def f(df):return df.age.count()
data_df.groupby('taste of mooncake').apply(f)

(二) 合并DataFrame: append, concat, join

# append
p=quotesdf[:2]
q=quotesdf['2018-01-01':'2018-01-05']
p.append(q)# concat
pieces=[tempdf[:5],tempdf[len(tempdf)-5:]]
pd.concat(pieces)

两个结构不同的DataFrame 如何合并?

piece1=quotesdf[0:3]
piece2=tempdf[:3]
pd.concat([piece1,piece2],ignore_index=True)

piece2有month 但是piece1中没有这个字段

join函数中的各种参数, 可以用来实现SQL的各种合并功能.

#join 两个dataframe要有共同的字段(列名)
#djidf: code/name
#AKdf:  volume/code/month
# 合并之后的字段: code/name/volume/month
pd.merge(djidf.drop(['lasttrade'],axis=1),AKdf, on='code')

道指30只成分股的股价及历史股价抓取分析相关推荐

  1. 微信公众号历史文章抓取

    微信公众号历史文章抓取 目录结构 WechatSpider │ README.md │ chromedriver.exe │ main.py │ gzhspider.py │ requirements ...

  2. 实现sohu社区′只看楼主′的功能,抓取连载帖子中楼主的所有帖子

    sohu社区(http://club.sohu.com/main.php),经常有一些不错的连载的帖子,少则几千个回复,多则可以上万个,可是最有用最想看的楼主的帖子也就几十个,从这些成千上万的帖子中, ...

  3. 30行jsoup代码搞定新浪微博登录抓取爬虫

    主要是设置cookies 想知道方法的朋友可以留言哦 爬虫问题都可以探讨哦 import java.io.IOException; import java.util.HashMap; import j ...

  4. 如何抓取微信公众号历史文章?使用订阅号实现微信公众号历史文章爬虫

        微信订阅号已经改版了,这篇文章已经过时了,不过可以提供还算有价值的参考.     微信公众号已经成为生活的一部分了,虽然里面有很多作者只是为了蹭热点,撩读者的 G 点,自己从中获得一些收益:但 ...

  5. 如何查询某只股票的历史股价?

    一个可以在线查询股票历史股价的小工具,目前可以查询A股.港股.美股所有个股的历史股价,另外还可以下载个股的历史股价Excel,做分析.研究挺有用的 只要两步就能下载: 填股票代码.邮箱 5分钟后收到股 ...

  6. mysql查询发生变化的股价_如何查询某只股票的历史股价?

    一个可以在线查询股票历史股价的小工具,目前可以查询A股.港股.美股所有个股的历史股价,另外还可以下载个股的历史股价Excel,做分析.研究挺有用的 只要两步就能下载:填股票代码.邮箱 5分钟后收到股票 ...

  7. 如何用Python进行历史股价分析

    如何用Python进行历史股价分析 一. 概述 二. 概念 三. 操作 3.1 统计分析 3.2 股票收益率 3.3 日期分析 3.4 周汇总 3.5 真实波动幅度均值 3.6 简单移动平均线 3.7 ...

  8. python爬取基金历史净值_Python学习笔记之抓取某只基金历史净值数据实战案例

    摘要:这篇Python开发技术栏目下的"Python学习笔记之抓取某只基金历史净值数据实战案例",介绍的技术点是"Python学习笔记.Python.历史净值数据.学习笔 ...

  9. python求鸡兔同笼 鸡兔总数鸡兔腿_编程解决鸡兔同笼的问题:假设共有鸡、兔30只,脚90只,求鸡、兔各有多少只? 提交代码和截图_学小易找答案...

    [判断题]链路是指两个相邻节点之间的通信线路 [简答题]编程实现以下功能: 输入一个文件夹,程序能够统计该文件夹的大小,以及该文件夹下子目录.子文件的数量. [简答题]如何正确使用食品添加剂? [简答 ...

  10. 如何通过Tushare获得A股历史股价数据

    如何通过Tushare pro获得A股历史股价数据 作者的 Tushare ID:418326 推荐:https://tushare.pro/register?reg=418326 摘要 上次分享了T ...

最新文章

  1. adb命令实现一些有趣的功能
  2. 知识点总结(基础篇)
  3. Codeforces Round #401 (Div. 1) C(set+树状数组)
  4. 【Node】node编译(windows)
  5. SDUT - 2604 Thrall’s Dream(tarjan+拓扑)
  6. Non-resolvable parent POM
  7. java 分号 转义_java – 正则表达式和转义和未转义的分隔符
  8. simhash与Google的网页去重(转)
  9. Oracle数据库关闭的三种方法
  10. iOS - OC 与 Swift 互相操作
  11. Switch基本知识
  12. Python自动发送邮件提示:smtplib.SMTPServerDisconnected: please run connect() first
  13. Delphi运行期错误
  14. [PSP3000完美破~解]5.03彻底告别刷机!让3K和V3可关机
  15. 利用FPGA实现出租车计费系统
  16. 【树莓派】使用VNC远程桌面
  17. 10个切片动作过渡PR预设
  18. iqc工作职责和工作内容_iqc工作职责流程
  19. HDLBits在线练习题之Exams/ece241 2014 q7b
  20. 【手把手】ElasticSearch的搜索推荐相关

热门文章

  1. javascript自定义浏览器右键菜单
  2. 因算法裁定“效率低下”,近150名员工遭解雇
  3. android 设置屏幕亮度,android 怎样设置屏幕亮度
  4. 聊聊图标和MBE图标
  5. linux终端清除命令,ubuntu清除命令行记录
  6. mysql数据库两表关联,【mysql两表关联查所有数据】
  7. java输出罗马数字_java工具类——罗马数字和阿拉伯数字相互转换
  8. 计算机坏处英语,玩电脑的危害英语作文,沉迷电脑的危害英语作文!
  9. 关于target is null for setProperty的问题总结
  10. templates模板文件