本博客是记录以及监督自己学习这本书中的内容,为了防止看过就忘记的弊端,简单地对本书进行一些必要的记录,也方便了日后的复习。
NumPy
NumPy是Python的一种开源的数值计算扩展,可用来存储和处理大型矩阵,比Python自身的列表结构要高效得多。NumPy底层使用BLAS作为向量,各种运算的速度也得打大幅提升。它主要包括:
Pandas
Pands的主要应用环境如下:
Pandas的底层基于NumPy搭建,因此Pandas拥有了NumPy的全部优点。
Matplotlib
Matplotlib是Python最著名的绘图库,提供了一整套和MATLAB相似的命令API,十分适合进行交互式制图。
Seaborn
Seaborn 其实是在Matplotlib 的基础上进行了更高级的API封装,从而使作图更容易。
应该把Seaborn 视为Matplotlib 的补充,而不是替代物。
SciPy
SciPy 包含致力于解决科学计算中常见的各个工具箱。它的不同子模块相当于不同的应用,例如差值、积分、优化、图像处理、特殊函数等。
Scikit-Learn
Scikit-Learn 是基于Python 的机器学习模块,基于BSD开源许可。
基本功能主要为:分类、回归、聚类、数据降维、模型选择和数据预处理。
对具体的机器学习问题的解决,通常可以分为三步:数据准备与预处理、模型选择与训练、模型验证与参数调优。Scikit-Learn封装了这些步骤,使建模的过程更方便、简单和快捷。
StatsModel
StatsModel 是Python 的统计建模和计量经济学工具包,包括一些描述统计、统计模型估计和推断,例如线性回归模型、广义线性回归模型、方差分析模型、时间序列模型、非参检验、优化、绘图功能等。
Quartz
Quartz 是优化的在线回测模块库,提供了跨资产多账户交易的量化策略框架,可以对策略进行专业的历史回测,得到详细的策略表现评估结果。它包括:多因子选股策略、事件驱动策略、CTA策略等。
特点如下:
CAL
CAL依托优矿量化实验室在线平台,基于C++ 开发高性能引擎,以 Python 作为接口语言向用户提供功能,他的宗旨是为广大投资者提供丰富、灵活的金融分析模块,降低投资者的分析平台搭建成本,帮助用户在金融大浪中顺利前行。
字符串:引号引起来的字符集。‘hello’、‘my python ’、‘2+3’等。可以是单引号、双引号和三引号。
#单引号
c1='Hello,Python'
print (c1)
c2='It is a "dog"!'
print (c2)
结果:Hello,Python
It is a "dog"!
转为大写字母
c1.upper()
结果显示:'HELLO,PYTHON'
c1[0] #获取第一个字母
结果显示:'H'
#双引号
c1="Hello,Python"
print (c1)
c2="It is a dog!"
print (c2)
#三引号
c3="""这
是
Python量化投资"""
print (c3)
结果显示:
Hello,Python
It is a dog!
这
是
Python量化投资
转义符
#转义符
print ('It\'s a dog!')
print ("hello boy\nhello boy")
结果显示:
It's a dog!
hello boy
hello boy
#自然字符串
print ("hello boy\nhello boy")
print (r"hello boy\nhello boy")
结果显示:
hello boy
hello boy
hello boy\nhello boy
字符串的重复
#字符串的重复
print ("我爱Python\n"*10)
结果显示:
我爱Python
我爱Python
我爱Python
我爱Python
我爱Python
我爱Python
我爱Python
我爱Python
我爱Python
我爱Python
切片运算
#子字符串
#索引运算符从0开始索引
#切片运算符[a:b]是指从第a下标开始到第b-1下标。同样第一位的下标为0,“包前不包后”
c1=u"wangxiaochuan"
c2=c1[0]
c3=c1[7]
c4=c1[:2]
c5=c1[2:]
c6=c1[4:7]
c7=c1[-1]
c8=c1[-3:]
cuts=[2,4,6]
c9=c1+c2
print (c2)
print (c3, c4, c5, c6,c7,c8,c9)
结果显示:
w
o wa ngxiaochuan xia n uan wangxiaochuanw
#列表
students=["小明","小华","小李","小娟","小云",3]
print (students[len(students)-1])
print (students[-1])
print (students[2])
结果显示:
3
3
小李
列表可以存放不同类型的数据,支持改写。
#列表元素支持修改
students=["小明","小华","小李","小娟","小云",3]
print (students[3])
students[3]="小月"
print (students[3])
students[5]="小楠"
print (students[5])
students[5]=19978
print (students[5])
结果显示:
小娟
小月
小楠
19978
#元组
students=("小明","小军","小强","小武","小龙")
print (students[1])
结果显示:
小军
元组比列表更加安全,因为不能修改,可以安全的保存一个引用,而不用担心里面的内容被其他程序修改,从而导致逻辑错误。
3. 集合
集合主要有两个功能:一个功能是进行集合操作,另一个功能是消除重复的元素。集合的格式是set(元素):
a=[1,2,3,4]
set(a)
结果显示:
{1, 2, 3, 4}
a=set("abcnmaaaaggsng")
print (a)
b=set("cdfm")
#交集
x=a&b
print (x)
print (a)
#并集
y=a|b
print (y)
#差集
z=b-a
print (z)
#去除重复元素
new=set(a)
print (new)
结果显示:
{'a', 'n', 'm', 'c', 's', 'g', 'b'}
{'c', 'm'}
{'a', 'n', 'm', 'c', 's', 'g', 'b'}
{'d', 'a', 'n', 'f', 'm', 'c', 's', 'g', 'b'}
{'f', 'd'}
{'a', 'n', 'm', 'c', 's', 'g', 'b'}
#字典
k={"姓名":"王小川","籍贯":"山东"}
print (k["籍贯"])
#添加字典里面的项目
k["爱好"]="游泳"
print (k["姓名"])
print (k["爱好"])
结果显示:
山东
王小川
游泳
Python 字典包含了很多的内置函数,比如比较两个字典元素。
常用关键字
#常用关键字
#查看一下关键字有哪些
import keyword
print (keyword.kwlist)
结果显示:
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
a='abc'
print (a.upper())
print (a.title())
结果显示:
ABC
Abc
#逻辑行与物理行
#以下是3个物理行
print ("abc")
print ("789")
print ("777")
#以下是1个物理行,3个逻辑行
print ("abc");print ("789");print ("777")
#以下是1个逻辑行,3个物理行
print ('''我是帅哥
王老师很帅
这是Python教程!''')
结果显示:
abc
789
777
abc
789
777
我是帅哥
王老师很帅
这是Python教程!
缩进
#如何缩进
#一般情况下,行首应该不留空白
import sys
#缩进的方法有两种,可以按空格,也可以按tab键
#if语句的缩进方法
a=7
if a>0:
print ("hello")
#while语句的缩进方法
a=0
while a<7:
print (a) # 思考下a为什么不包含7
a+=1
a=100
结果显示:
hello
0
1
2
3
4
5
6
#"+":两个对象相加
#两个数字相加
a=7+8
print (a)
#两个字符串相加
b="GOOD"+" JOB!"
print (b)
#"-":取一个数字的相反数或者实现两个数字相减
a=-7
print (a)
b=-(-8)
print (b)
c=19-1
print (c)
#"*":两个数相乘或者字符串重复
a=4*7
print (a)
b="hello"*3
print (b)
b="hello\n"*3
print (b)
#"/":两个数字相除
a=7/2
print (a)
b=7.0/2
c=7/2.0
print (b)
print (c)
from __future__ import division
a=7/2
print (a)
#"**":求幂运算
a=2**3 #相当于2的3次幂,就是2*2*2
print (a)
#"//":除法运算,然后返回其商的整数部分,舍掉余数
a=10//3
print (a)
#"%":除法运算,然后返回其商的余数部分,舍掉商
a=10%3
print (a)
b=10%1 #没有余数的时候返回什么?
print (b)
#"<":小于符号,返回一个bool值
a=3<7
print (a)
b=3<3
print (b)
type(a)
#">":大于符号,返回一个bool值
a=3>7
print (a)
b=3>1
print (b)
#"!=":不等于符号,同样返回一个bool值
a=2!=3
print (a)
b=2!=2
print (b)
#"<=":小于等于符号,比较运算,小于或等于,返回一个bool值
a=3<=3
print (a)
b=4<=3
print (b)
#">="
a=1>=3
print (a)
b=4>=3
print (b)
#"==":比较两个对象是否相等
a=12==13
print (a)
b="hello"=="hello"
print (b)
#not:逻辑非
a=True
b=not a
print (b)
c=False
print (not c)
#and:逻辑与
'''
True and True等于True
True and False等于False
False and True等于False
'''
print (True and True)
#or:逻辑或
'''
True or True等于True
True or False等于True
False or False等于False
'''
print (True or False)
我们通常根据不同的需要来选择控制语句,以控制某些代码段的执行方式,这些不同功能的控制语句就叫做控制流。
两种方式实现同一功能
i=1
print (i)
i=i+1
print (i)
i=1
print (i)
i=i+1
print (i)
结果显示:
1
2
1
2
for k in range(0,2):
i=1
print (i)
i=i+1
print (i)
结果显示:
1
2
1
2
weather="rainy"
if weather=="sunny":
print ("basketball")
else:
print ("badminton")
结果显示:
badminton
a=1
print (a)
a=a-1
print (a)
a=a+2
print (a)
结果显示:
1
0
2
a=0
if a==1:
print ("She")
else:
print ("He")
结果显示:
He
for i in range(5):
print ("hello world")
print (i)
结果显示:
hello world
0
hello world
1
hello world
2
hello world
3
hello world
4
while 结构
i=5
while i:
print ("hello world")
print (i)
i=i-1
结果显示:
hello world
5
hello world
4
hello world
3
hello world
2
hello world
1
在一种情况下的if用法
#在一种情况下的if用法
a=8
if a==8: #这里的等号注意是==,而非=
print ("hello world")
结果显示:
hello world
在两种选择情况下的if用法
#在两种选择情况下的if用法
a=9
if a==9:
print ("hello world")
else:
print ("Null")
结果显示:
hello world
在三种选择情况下的if用法
#在三种选择情况下的if用法
a=10
if a==10:
print ("hello world")
elif a>8:
print ("hello")
elif a>6:
print ("world")
else:
print ("Null")
结果显示:
hello world
使用要点如下:
各分支尽量不重复,并且尽量包含全部可能性;
在if 语句里还可以再写if 语句,形成if 语句的嵌套;
elif 和 else 语句永远只是可选的;
在Python中没有 switch 语句。
for i in [1,2,3,4,5]:
print (i)
结果显示:
1
2
3
4
5
for i in range(1,10,3):
print ("hello")
print (i)
结果显示:
hello
1
hello
4
hello
7
char=u"你好世界" #U代表这是Unicode编码
tem=("元组:你好","元组:世界")
list=["列表:你好","列表:世界"]
dict={"first":"字典:你好","second":"字典:世界"}
for i in char:
print (i)
for i in tem:
print (i)
for i in list:
print (i)
for i in dict:
print (i)
结果显示:
你
好
世
界
元组:你好
元组:世界
列表:你好
列表:世界
first
second
使用要点:
适当运用range 、 xrange函数;
在for 中还可以再写for ,形成循环嵌套;
合理地运用lambda 代替 for 循环,可以提高运行速度。
a=True
while a:
print ("hello world")
无限循环 hello world
b=False
while b:
print ("hello world")
else:
print ("Null")
a=1
while a<5:
if a<=3:
print (a)
else:
print ("hello")
a=a+1
结果显示:
1
2
3
hello
for i in range(5,9):
print (i)
print ("hello world")
if i>6:
break
结果显示:
5
hello world
6
hello world
7
hello world
a=5
while a<=8:
a=a+1
for i in range(1,3):
print (a,i)
if i==2:
break
结果显示:
6 1
6 2
7 1
7 2
8 1
8 2
9 1
9 2
continue 语句 停止循环中的这一次执行,直接跳到下一次执行。
n = 0
while n < 10:
n = n + 1
if n % 2 == 0: # 如果n是偶数,则执行continue语句
continue# continue语句会直接继续下一轮循环,后续的print()语句不会执行
print (n)
结果显示:
1
3
5
7
9
for n in range(1,10):
if n%2==0:
continue
print (n)
结果显示:
1
3
5
7
9
a=1
while a<7:
a=a+1
if a==4:
continue
for i in range(7,10):
if i==9:
continue
print (i)
结果显示:
7
8
7
8
7
8
7
8
7
8
continue 语句指的是结束执行本次循环中的剩余的语句,然后继续执行下一轮的循环;
break 语句指的是直接结束这个循环,包括结束执行该循环的剩余的所有次循环。
for i in range(10,19):
if i==15:
continue
print (i)
结果显示:
10
11
12
13
14
16
17
18
for i in range(10,19):
if i==15:
break
print (i)
结果显示:
10
11
12
13
14
Python中的函数功能
a="ace"
print (len(a))
3
a="student,my xxxx"
b=a.split('t')
print (b)
['s', 'uden', ',my xxxx']
a.upper()
'STUDENT,MY XXXX'
在Python中定义函数
def function1():
a=9
a+=8
print (a)
function1()
17
a="abcdm"
print (len(a))
5
形参
def function(a,b):
if a>b:
print (a)
else:
print (b)
function(4,5)
5
实参
def function1(a,b):
if a>b:
return 'a+b'
else:
return 'a-b'
a=function1(1,3)
print (a)
a-b
参数的传递
def function(a=1,b=0):
if a>b:
return a
else:
return b
max=function(7,8)
print (max)
8
function()
1
a=9
b=10
c=1
def function(add=0,b=0,c=0):
print (add)
print (b)
print (c)
function(a,c,b)
9
1
10
function(add=a,b=b,c=c)
9
10
1
function(b=7,add=8)
8
7
0
function(c=2,b=3,add=5)
5
3
2
作用域: 一个变量在一定的范围内起作用。
i=10 #这里定义一个全局变量i
print (i)
10
def func():
i=8 #给局部变量i赋值
func()
print (i)
10
局部变量
i=2 #给全局变量i赋值
def func2(a):
i=7 #给局部变量i赋值
print (i)
func2(1)
print (i)
7
2
func2(i)
7
print (i)
2
全局变量
def func3():
global i
i=7
a=func3()
print (a)
print (i)
None
7
i=7
def func3 ():
i=1
func3 () #调用函数
print (i)
7
函数的返回值
def test():
i=7
return i
print (test())
7
def test2(i,j):
k=i*j
return (i,j,k)
a=test2(4,5)
print (a)
4 5 20
def d(i,j):
'''这个函数实现一个乘法运算。
函数会返回一个乘法运算的结果。'''
k=i*j
return k
help(d)
Help on function d in module __main__:
d(i, j)
这个函数实现一个乘法运算。
函数会返回一个乘法运算的结果。
通过对文档字符串的说明,我们就可以明白这个函数的功能及所返回结果的属性。
import pandas
import pandas as pd
通过from import 导入整个模块
from pandas import Series
sys 模块
我们把在标准库中与系统功能有关的这些模块叫做sys 模块。
import sys
print (sys.argv[0])
sys.getdefaultencoding()
'utf-8'
from pandas import DataFrame
df1 = DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'], 'data1': range(7)})
df1.head(2)
data1 key
0 0 b
1 1 b
from pandas import *
df1 = DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'], 'data1': range(7)})
df1.head(2)
data1 key
0 0 b
1 1 b
print (__name__)
__main__
if __name__=="__main__":
print ("It's main")
else:
print ("It's not main")
It's main
自定义模块:需要我们自己定义和编写
定义一点代码,保存,调用
dir()函数
通过dir()函数来查看指定模块的功能列表。
import pandas
dir(pandas)
还能查看任意指定对象的功能列表。
a = [1]
dir(a)
class SoSError(Exception): #按照命名规范,以Error结尾,并且自定义异常需要继承Exception类
def __init__(self):
Exception.__init__(self)
try:
i=8
if i>7:
raise SoSError()
except SoSError:
print ("SoSError:我错了")
SoSError:我错了
#假如要实现不管中间是否发生异常,都要输出hello world
try:
print (w)
finally:
print ("不管上面是否异常,我必须输出hello world!")
不管上面是否异常,我必须输出hello world!
创建某个文件
#创建某个文件
import os
os.mkdir(r"d:/newdir")
文件的基本操作:增、删、查、改。