30天学会量化交易模型 Day05
这一节 我们学习如何把得到的数据写入数据库。
虽然也可以写入excel或者json,不过考虑到后面用的的排序和其他python脚本的调用,最后选择了轻量级的数据库SQLiite作为首选。
# -*-coding=utf-8-*-
#数据库的操作
'''
http://30daydo.com
weigesysu@qq.com
'''
import sqlite3, time, datetime
__author__ = 'rocky'
class SqliteDb():
def __init__(self,dbtable):
'''
self.today = time.strftime("%Y-%m-%d")
self.DBname = self.today + '.db'
self.conn = sqlite3.connect(self.DBname)
'''
today = time.strftime("%Y-%m-%d")
DBname = today + '.db'
self.conn = sqlite3.connect(DBname)
self.dbtable=dbtable
create_tb = "CREATE TABLE %s (date varchar(10),id varchar(6), name varchar(30), p_change REAL,turnover REAL);" %self.dbtable
self.conn.execute(create_tb)
self.conn.commit()
def store_break_high(self,price_high_data):
#data 是创新高的个股信息 dataframe
#print today
#create_tb = 'CREATE TABLE STOCK (date TEXT,id text PRIMARY KEY, p_change REAL,turnover REAL);'
#conn.commit()
#print "(%s,%s,%f,%f)" %(price_high_data[0], price_high_data[1], price_high_data[2], price_high_data[3])
insert_data_cmd = "INSERT INTO %s(date,id,name,p_change,turnover) VALUES(\"%s\",\"%s\",\"%s\",%f,%f);" %(self.dbtable,price_high_data[0], price_high_data[1], price_high_data[2], price_high_data[3],price_high_data[4])
self.conn.execute(insert_data_cmd)
#self.conn.execute('INSERT INTO STOCK(date,id,name,p_change,turnover) VALUES(?,?,?,?,?)',(price_high_data[0], price_high_data[1], price_high_data[2], price_high_data[3],price_high_data[4]))
self.conn.commit()
def close(self):
self.conn.close()
上面创建的表名是 以日期为命名的(前面的下划线是因为数据库的命名规则不能以数字为首)
上一篇:30天学会量化交易模型 Day04 (tushare获取破新高的股票)
http://www.30daydo.com/article/70 收起阅读 »
使用pandas的dataframe数据进行操作的总结
#使用iloc后,t已经变成了一个子集。 已经不再是一个dataframe数据。 所以你使用 t['high'] 返回的是一个值。此时t已经没有index了,如果这个时候调用 t.index
t=df[:1]
class 'pandas.core.frame.DataFrame'>
#这是返回的是一个DataFrame的一个子集。 此时 你可以继续用dateFrame的一些方法进行操作。
删除dataframe中某一行
df.drop()
df的内容如下:
df.drop(df[df[u'代码']==300141.0].index,inplace=True)
print df
输出如下
记得参数inplace=True, 因为默认的值为inplace=False,意思就是你不添加的话就使用Falase这个值。
这样子原来的df不会被修改, 只是会返回新的修改过的df。 这样的话需要用一个新变量来承接它
new_df=df.drop(df[df[u'代码']==300141.0].index)
判断DataFrame为None
if df is None:
print "None len==0"
return False
收起阅读 »
30天学会量化交易模型 Day04
股市有句话,新高后有新高。
因为新高后说明消化了前面的套牢盘。 所以这个时候的阻力很小。
下面使用一个例子来用代码获取当天创新高的股票。
使用的是tushare
#-*-coding=utf-8-*-
__author__ = 'rocky'
'''
http://30daydo.com
weigesysu@qq.com
'''
#获取破指定天数内的新高 比如破60日新高
import tushare as ts
import datetime
info=ts.get_stock_basics()
def loop_all_stocks():
for EachStockID in info.index:
if is_break_high(EachStockID,60):
print "High price on",
print EachStockID,
print info.ix[EachStockID]['name'].decode('utf-8')
def is_break_high(stockID,days):
end_day=datetime.date(datetime.date.today().year,datetime.date.today().month,datetime.date.today().day)
days=days*7/5
#考虑到周六日非交易
start_day=end_day-datetime.timedelta(days)
start_day=start_day.strftime("%Y-%m-%d")
end_day=end_day.strftime("%Y-%m-%d")
df=ts.get_h_data(stockID,start=start_day,end=end_day)
period_high=df['high'].max()
#print period_high
today_high=df.iloc[0]['high']
#这里不能直接用 .values
#如果用的df【:1】 就需要用.values
#print today_high
if today_high>=period_high:
return True
else:
return False
loop_all_stocks()
可以修改 函数 is_break_high(EachStockID,60) 中的60 为破多少天内的新高。
上一篇:30天学会量化交易模型 Day03
http://www.30daydo.com/article/15
下一篇: 30天学会量化交易模型 Day05 (tushare数据写入SQLite)
http://www.30daydo.com/article/73 收起阅读 »
安卓系统常用命令 adb shell
1. 安卓关机(非重启): adb shell svc power shutdown
2. android开机的时候跳过初始化设置 (setup wizard): adb shell input text 1396611460
3.
雪人股份 继续跟踪 7月12日
所以后期还是可以再介入一波。
雪人股份 后续分析 6月30日 收起阅读 »
python 爬虫下载的图片打不开?
代码如下片段
__author__ = 'rocky'运行后生成的文件打开后不显示图片。
import urllib,urllib2,StringIO,gzip
url="http://image.xitek.com/photo/2 ... ot%3B
filname=url.split("/")[-1]
req=urllib2.Request(url)
resp=urllib2.urlopen(req)
content=resp.read()
#data = StringIO.StringIO(content)
#gzipper = gzip.GzipFile(fileobj=data)
#html = gzipper.read()
f=open(filname,'w')
f.write()
f.close()
后来调试后发现,如果要保存为图片格式, 文件的读写需要用'wb', 也就是上面代码中
f=open(filname,'w') 改一下 改成
f=open(filname,'wb')
就可以了。
收起阅读 »
定向增发与非公开发行
定向增发与非公开发行目前已经是一个概念了。
定向增发是指上市公司向符合条件的少数特定投资者非公开发行股份的行为,规定要求发行对象不得超过10人,发行价不得低于公告前20个交易市价的90%,发行股份12个月内(认购后变成控股股东或拥有实际控制权的36个月内) 不得转让。
2006年证监会推出的《再融资管理办法》中,关于非公开发行,除了规定发行对象不得超过10人,发行价不得低于市价的90%,发行股份12个月内(大股东认购的为36个月)不得转让,以及募资用途需符合国家产业政策、上市公司及其高管不得有违规行为等外,没有其他条件。
感觉不公开的东西才是好东东~
非定向增发的估计都是没人要的。。 收起阅读 »
python 编写火车票抢票软件
实现日期:2016.7.30
python 获取 中国证券网 的公告
这个网站的公告会比同花顺东方财富的早一点,而且还出现过早上中国证券网已经发了公告,而东财却拿去做午间公告,以至于可以提前获取公告提前埋伏。
现在程序自动把抓取的公告存入本网站中:http://30daydo.com/news.php
每天早上8:30更新一次。
生成的公告保存在stock/文件夹下,以日期命名。 下面脚本是循坏检测,如果有新的公告就会继续生成。
默认保存前3页的公告。(一次过太多页会被网站暂时屏蔽几分钟)。 代码以及使用了切换header来躲避网站的封杀。
修改
getInfo(3) 里面的数字就可以抓取前面某页数据
__author__ = 'rocchen'
# working v1.0
from bs4 import BeautifulSoup
import urllib2, datetime, time, codecs, cookielib, random, threading
import os,sys
def getInfo(max_index_user=5):
stock_news_site =
"http://ggjd.cnstock.com/gglist/search/ggkx/"
my_userAgent = [
'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0',
'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)',
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
'Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
'Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11',
'Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)']
index = 0
max_index = max_index_user
num = 1
temp_time = time.strftime("[%Y-%m-%d]-[%H-%M]", time.localtime())
store_filename = "StockNews-%s.log" % temp_time
fOpen = codecs.open(store_filename, 'w', 'utf-8')
while index < max_index:
user_agent = random.choice(my_userAgent)
# print user_agent
company_news_site = stock_news_site + str(index)
# content = urllib2.urlopen(company_news_site)
headers = {'User-Agent': user_agent, 'Host': "ggjd.cnstock.com", 'DNT': '1',
'Accept': 'text/html, application/xhtml+xml, */*', }
req = urllib2.Request(url=company_news_site, headers=headers)
resp = None
raw_content = ""
try:
resp = urllib2.urlopen(req, timeout=30)
except urllib2.HTTPError as e:
e.fp.read()
except urllib2.URLError as e:
if hasattr(e, 'code'):
print "error code %d" % e.code
elif hasattr(e, 'reason'):
print "error reason %s " % e.reason
finally:
if resp:
raw_content = resp.read()
time.sleep(2)
resp.close()
soup = BeautifulSoup(raw_content, "html.parser")
all_content = soup.find_all("span", "time")
for i in all_content:
news_time = i.string
node = i.next_sibling
str_temp = "No.%s \n%s\t%s\n---> %s \n\n" % (str(num), news_time, node['title'], node['href'])
#print "inside %d" %num
#print str_temp
fOpen.write(str_temp)
num = num + 1
#print "index %d" %index
index = index + 1
fOpen.close()
def execute_task(n=60):
period = int(n)
while True:
print datetime.datetime.now()
getInfo(3)
time.sleep(60 * period)
if __name__ == "__main__":
sub_folder = os.path.join(os.getcwd(), "stock")
if not os.path.exists(sub_folder):
os.mkdir(sub_folder)
os.chdir(sub_folder)
start_time = time.time() # user can change the max index number getInfo(10), by default is getInfo(5)
if len(sys.argv) <2:
n = raw_input("Input Period : ? mins to download every cycle")
else:
n=int(sys.argv[1])
execute_task(n)
end_time = time.time()
print "Total time: %s s." % str(round((end_time - start_time), 4))
github:https://github.com/Rockyzsu/cnstock
收起阅读 »
雪人股份 后续分析 6月30日
从27日的龙虎榜信息来看
卖出方并没有出现福州五一路,说明该营业部进行了锁仓。 而从最近2天的调整的套路来看,成交量减少了一半,主力不可能在2天缩量的时候把货出掉,所以判断是锁仓。。 分时上看,一旦股价下跌到最低点(下图中的红圈),就有大单涌进来吸货。 从而并未造成股价大幅下跌。
如果庄家跑路,那么股价就会随自由落体,价格波动幅度会很大。
所有雪人后续还会有一批,建议目前小仓位建仓,等股价拉起来可以继续加仓。
雪人股份 分析贴:
雪人股份 后续分析 6月22日
雪人股份 大宗交易分析 寻找主力痕迹
收起阅读 »
python 下使用beautifulsoup还是lxml ?
然后看了下beautifulsoup的源码,其实现原理使用的是正则表达式,而lxml使用的节点递归的技术。
Don't use BeautifulSoup, use lxml.soupparser then you're sitting on top of the power of lxml and can use the good bits of BeautifulSoup which is to deal with really broken and crappy HTML.
9down vote
In summary,lxmlis positioned as a lightning-fast production-quality html and xml parser that, by the way, also includes asoupparsermodule to fall back on BeautifulSoup's functionality.BeautifulSoupis a one-person project, designed to save you time to quickly extract data out of poorly-formed html or xml.
lxml documentation says that both parsers have advantages and disadvantages. For this reason,lxmlprovides asoupparserso you can switch back and forth. Quoting,
[quote]
BeautifulSoup uses a different parsing approach. It is not a real HTML parser but uses regular expressions to dive through tag soup. It is therefore more forgiving in some cases and less good in others. It is not uncommon that lxml/libxml2 parses and fixes broken HTML better, but BeautifulSoup has superiour support for encoding detection. It very much depends on the input which parser works better.
In the end they are saying,
The downside of using this parser is that it is much slower than the HTML parser of lxml. So if performance matters, you might want to consider using soupparser only as a fallback for certain cases.
If I understand them correctly, it means that the soup parser is more robust --- it can deal with a "soup" of malformed tags by using regular expressions --- whereas
lxmlis more straightforward and just parses things and builds a tree as you would expect. I assume it also applies to
BeautifulSoupitself, not just to the
soupparserfor
lxml.
They also show how to benefit from
BeautifulSoup's encoding detection, while still parsing quickly with
lxml:
[code]>>> from BeautifulSoup import UnicodeDammit[/code]
>>> def decode_html(html_string):
... converted = UnicodeDammit(html_string, isHTML=True)
... if not converted.unicode:
... raise UnicodeDecodeError(
... "Failed to detect encoding, tried [%s]",
... ', '.join(converted.triedEncodings))
... # print converted.originalEncoding
... return converted.unicode
>>> root = lxml.html.fromstring(decode_html(tag_soup))
(Same source: http://lxml.de/elementsoup.html).
In words of
BeautifulSoup's creator,
That's it! Have fun! I wrote Beautiful Soup to save everybody time. Once you get used to it, you should be able to wrangle data out of poorly-designed websites in just a few minutes. Send me email if you have any comments, run into problems, or want me to know about your project that uses Beautiful Soup.[code] --Leonard
[/code]
Quoted from the Beautiful Soup documentation.
I hope this is now clear. The soup is a brilliant one-person project designed to save you time to extract data out of poorly-designed websites. The goal is to save you time right now, to get the job done, not necessarily to save you time in the long term, and definitely not to optimize the performance of your software.
Also, from the lxml website,
lxml has been downloaded from the Python Package Index more than two million times and is also available directly in many package distributions, e.g. for Linux or MacOS-X.
And, from Why lxml?,
The C libraries libxml2 and libxslt have huge benefits:... Standards-compliant... Full-featured... fast. fast! FAST! ... lxml is a new Python binding for libxml2 and libxslt...
[/quote]
意思大概就是 不要用Beautifulsoup,使用lxml, lxml才能让你提要到让你体会到html节点解析的速度之快。
收起阅读 »
python 批量获取色影无忌 获奖图片
不多说,直接来代码:
#-*-coding=utf-8-*-
__author__ = 'rocky chen'
from bs4 import BeautifulSoup
import urllib2,sys,StringIO,gzip,time,random,re,urllib,os
reload(sys)
sys.setdefaultencoding('utf-8')
class Xitek():
def __init__(self):
self.url="http://photo.xitek.com/"
user_agent="Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"
self.headers={"User-Agent":user_agent}
self.last_page=self.__get_last_page()
def __get_last_page(self):
html=self.__getContentAuto(self.url)
bs=BeautifulSoup(html,"html.parser")
page=bs.find_all('a',class_="blast")
last_page=page[0]['href'].split('/')[-1]
return int(last_page)
def __getContentAuto(self,url):
req=urllib2.Request(url,headers=self.headers)
resp=urllib2.urlopen(req)
#time.sleep(2*random.random())
content=resp.read()
info=resp.info().get("Content-Encoding")
if info==None:
return content
else:
t=StringIO.StringIO(content)
gziper=gzip.GzipFile(fileobj=t)
html = gziper.read()
return html
#def __getFileName(self,stream):
def __download(self,url):
p=re.compile(r'href="(/photoid/\d+)"')
#html=self.__getContentNoZip(url)
html=self.__getContentAuto(url)
content = p.findall(html)
for i in content:
print i
photoid=self.__getContentAuto(self.url+i)
bs=BeautifulSoup(photoid,"html.parser")
final_link=bs.find('img',class_="mimg")['src']
print final_link
#pic_stream=self.__getContentAuto(final_link)
title=bs.title.string.strip()
filename = re.sub('[\/:*?"<>|]', '-', title)
filename=filename+'.jpg'
urllib.urlretrieve(final_link,filename)
#f=open(filename,'w')
#f.write(pic_stream)
#f.close()
#print html
#bs=BeautifulSoup(html,"html.parser")
#content=bs.find_all(p)
#for i in content:
# print i
'''
print bs.title
element_link=bs.find_all('div',class_="element")
print len(element_link)
k=1
for href in element_link:
#print type(href)
#print href.tag
'''
'''
if href.children[0]:
print href.children[0]
'''
'''
t=0
for i in href.children:
#if i.a:
if t==0:
#print k
if i['href']
print link
if p.findall(link):
full_path=self.url[0:len(self.url)-1]+link
sub_html=self.__getContent(full_path)
bs=BeautifulSoup(sub_html,"html.parser")
final_link=bs.find('img',class_="mimg")['src']
#time.sleep(2*random.random())
print final_link
#k=k+1
#print type(i)
#print i.tag
#if hasattr(i,"href"):
#print i['href']
#print i.tag
t=t+1
#print "*"
'''
'''
if href:
if href.children:
print href.children[0]
'''
#print "one element link"
def getPhoto(self):
start=0
#use style/0
photo_url="http://photo.xitek.com/style/0/p/"
for i in range(start,self.last_page+1):
url=photo_url+str(i)
print url
#time.sleep(1)
self.__download(url)
'''
url="http://photo.xitek.com/style/0/p/10"
self.__download(url)
'''
#url="http://photo.xitek.com/style/0/p/0"
#html=self.__getContent(url)
#url="http://photo.xitek.com/"
#html=self.__getContentNoZip(url)
#print html
#'''
def main():
sub_folder = os.path.join(os.getcwd(), "content")
if not os.path.exists(sub_folder):
os.mkdir(sub_folder)
os.chdir(sub_folder)
obj=Xitek()
obj.getPhoto()
if __name__=="__main__":
main()
下载后在content文件夹下会自动抓取所有图片。 (色影无忌的服务器没有做任何的屏蔽处理,所以脚本不能跑那么快,可以适当调用sleep函数,不要让服务器压力那么大)
已经下载好的图片:
github: https://github.com/Rockyzsu/fetchXitek (欢迎前来star) 收起阅读 »
房事一谈
换手率 你未必懂的地方
很多人都知道换手率代表一个股票的活跃程度,不过里面还是有一些不为人知的地方。
比如: 近期的新股 中国核建
换手率为0.52%, 看起来很低吧。
可是很多人忽略了一个地方,换手率的公式= 当天成交股票股数/流通股本, 而对于很多新股来说,会有很大部分的禁售股, 中国核建总股本26亿,而流通股才5亿多,超过20亿股本是暂时无法流通的,所以目前在市场上活跃的股本才5亿, 也就是真正的换手率 为 = 当日成交股票股数/流通股本 , 对于中国核建来说,它的实际换手率为 = 2.73万*100/5.25亿 * 100% = 0.52%
而对于新股来说,一般如果换手超过2%,下一天很可能就会开板。对于次新股来说,还可以接到1~2个涨停板左右。
收起阅读 »
阻挡黑客的最原始最暴力的方法 ---用胶带粘住你的摄像头
扎克为什么要把摄像头蒙住呢?这得先说一下 Ratting(Remote Access Trojan)这种行为。所谓的 Ratting,是指黑客通过植入木马远程控制受害用户设备的行为,而进行这种行为的黑客一般叫做 ratter。除了窃取设备的敏感数据以外,激活用户摄像头和麦克风偷拍视频也是 ratter 常干的事情。
不过扎克伯格这么专业的人也把摄像头蒙起来究竟是偏执狂还是好做法呢?安全专家认为是后者,原因有三:
一是扎克伯格是一个高价值的攻击目标。无论是情报机构还是为了罪犯无疑都会对扎克伯格的资料虎视眈眈,而对于那些为了证明自己黑客功力的人来说,扎克也是一个很理想的目标。所以采取预防措施是很自然的事情。
二是把采集音视频的入口盖住是一种成本低廉且基本的安全防护办法。如果想窃听安全会议,有经验的黑客一般都会先数数哪些设备没有遮住摄像头然后再确定下手的目标。
三是扎克未必就不会被攻破。事实上本月初就爆出了黑客袭击扎克伯格部分社交网络,盗取了他的 Twitter、Pinterest、LinkedIn 帐号的消息。把这两件事联系在一起,更容易解释他的那台 Macbook 上面的胶带。
事实上,采取这种做法的人并不止扎克一个。就连 FBI 局长 James Comey 也把自己的笔记本摄像头蒙上了胶带—原因很简单,因为他看到一个比他更聪明的人也这么干。所以你要不要也蒙上呢? 收起阅读 »
python使用lxml加载 html---xpath
然后按照以下代码去使用
#-*-coding=utf-8-*-
__author__ = 'rocchen'
from lxml import html
from lxml import etree
import urllib2
def lxml_test():
url="http://www.caixunzz.com"
req=urllib2.Request(url=url)
resp=urllib2.urlopen(req)
#print resp.read()
tree=etree.HTML(resp.read())
href=tree.xpath('//a[@class="label"]/@href')
#print href.tag
for i in href:
#print html.tostring(i)
#print type(i)
print i
print type(href)
lxml_test()
使用urllib2读取了网页内容,然后导入到lxml,为的就是使用xpath这个方便的函数。 比单纯使用beautifulsoup要方便的多。(个人认为) 收起阅读 »
mac os x 下 git gui 好用的图形工具
试了几个工具,最好用的还是sourcetree。 跨平台,win和mac都可以用,而且注册账号后还可以在云上同步。


https://www.sourcetreeapp.com/download/ 收起阅读 »
雪人股份 后续分析 6月22日
在上一篇 文章中,雪人股份 大宗交易分析 寻找主力痕迹 我们找到了该股接盘的营业部----福州五一路。
今天龙虎榜上:
没有出现任何的福州的营业部,所以该游资对雪人股份进行了锁仓处理。 而且 溧阳路 还进来了,所以后来会有一波洗盘以及拉升。 (鉴于溧阳路的风格)
收起阅读 »
浙江世宝的十大股东之一,柳青
所以这里的柳青很有可能是柳传志之女柳青,滴滴公司的总裁。
百度百科的资料
柳青
(柳传志之女,滴滴出行总裁)
编辑柳青, 1978年出生于北京,毕业于北京大学和哈佛大学,现任滴滴出行总裁。
2000年,柳青毕业于北京大学计算机系毕业,随后进入哈佛大学学习。2002年获哈佛大学硕士学位,同年入职高盛(亚洲)有限责任公司。2008年晋升为高盛(亚洲)有限责任公司执行董事,凭借努力,逐步晋升为高盛亚洲区董事总经理,成为这家百年投行历史上最年轻的董事总经理。
2014年,柳青加盟滴滴出任首席运营官,2015年2月升任滴滴总裁。柳青与程维成为搭档后,主导了滴滴打车与快的打车的合并[1] 。2015年柳青与滴滴出行董事长程维同时登上财富全球四十精英榜榜首[2] 。同年,世界经济论坛也授予柳青“全球青年领袖”称号[3] 。2015 年柳青入选财富“中国最具影响力的 25 位商界女性” [4] ;2013和2014年,两次被《中国企业家》评选为“中国最有影响力商界女性” [5] 。柳青是北京青联委员、哈佛大学研究生院校友会理事[6] ,壹基金理事会理事[7] 。 收起阅读 »