Python量化教程 常用函数

# -*- coding: utf-8 -*-
# @Author: fangbei
# @Date:   2017-08-26
# @Original:


price_str = '30.14, 29.58, 26.36, 32.56, 32.82'
price_str = price_str.replace(' ', '')  #删除空格
price_array = price_str.split(',')      #转成数组



date_array = []
date_base = 20170118
'''
# for 循环
for _ in range(0, len(price_array)):
    date_array.append(str(date_base))
    date_base += 1
'''

#推导式comprehensions(又称解析式),是Python的一种独有特性。推导式是可以从一个数据序列构建另一个新的数据序列的结构体。

#列表推导式
date_array = [str(date_base + ind) for ind, _ in enumerate(price_array)]
print(date_array)
# ['20170118', '20170119', '20170120', '20170121', '20170122']



# zip函数
stock_tuple_list = [(date, price) for date, price in zip(date_array, price_array)]
print(stock_tuple_list)
# [('20170118', '30.14'), ('20170119', '29.58'), ('20170120', '26.36'), ('20170121', '32.56'), ('20170122', '32.82')]

#字典推导式
stock_dict = {date: price for date, price in zip(date_array, price_array)}
print(stock_dict)
# {'20170118': '30.14', '20170119': '29.58', '20170120': '26.36', '20170121': '32.56', '20170122': '32.82'}


# 可命名元组 namedtuple
from collections import namedtuple
stock_nametuple = namedtuple('stock', ('date', 'price'))
stock_nametuple_list = [stock_nametuple(date, price) for date, price in zip(date_array, price_array)]
print(stock_nametuple_list)
# [stock(date='20170118', price='30.14'), stock(date='20170119', price='29.58'), stock(date='20170120', price='26.36'), stock(date='20170121', price='32.56'), stock(date='20170122', price='32.82')]


# 有序字典 OrderedDict
from collections import OrderedDict
stock_dict = OrderedDict((date, price) for date, price in zip(date_array, price_array))
print(stock_dict.keys())
# odict_keys(['20170118', '20170119', '20170120', '20170121', '20170122'])

#最小收盘价
print(min(zip(stock_dict.values(), stock_dict.keys())))
# ('26.36', '20170120')

#lambad函数
func = lambda x:x+1
#以上lambda等同于以下函数
def func(x):
    return(x+1)
#找出收盘价中第二大的价格
find_second_max_lambda = lambda dict_array : sorted(zip(dict_array.values(), dict_array.keys()))[-2]
print(find_second_max_lambda(stock_dict))
# ('32.56', '20170121')


#高阶函数
#将相邻的收盘价格组成tuple后装入list
price_float_array = [float(price_str) for price_str in stock_dict.values()]
pp_array = [(price1, price2) for price1, price2 in zip(price_float_array[:-1], price_float_array[1:])]
print(pp_array)
# [(30.14, 29.58), (29.58, 26.36), (26.36, 32.56), (32.56, 32.82)]

from functools import reduce
#外层使用map函数针对pp_array()的每一个元素执行操作,内层使用reduce()函数即两个相邻的价格, 求出涨跌幅度,返回外层结果list
change_array = list(map(lambda pp:reduce(lambda a,b: round((b-a) / a, 3),pp), pp_array))
# print(type(change_array))


change_array.insert(0,0)
print(change_array)
# [0, -0.019, -0.109, 0.235, 0.008]

#将涨跌幅数据加入OrderedDict,配合使用namedtuple重新构建数据结构stock_dict
stock_nametuple = namedtuple('stock', ('date', 'price', 'change'))
stock_dict = OrderedDict((date, stock_nametuple(date, price, change))
                         for date, price, change in
                         zip(date_array, price_array, change_array))
print(stock_dict)
# OrderedDict([('20170118', stock(date='20170118', price='30.14', change=0)), ('20170119', stock(date='20170119', price='29.58', change=-0.019)), ('20170120', stock(date='20170120', price='26.36', change=-0.109)), ('20170121', stock(date='20170121', price='32.56', change=0.235)), ('20170122', stock(date='20170122', price='32.82', change=0.008))])
#用filter()进行筛选,选出上涨的交易日
up_days = list(filter(lambda day: day.change > 0, stock_dict.values()))
print(up_days)
# [stock(date='20170121', price='32.56', change=0.235), stock(date='20170122', price='32.82', change=0.008)]


#定义函数计算涨跌日或涨跌值
def filter_stock(stock_array_dict, want_up=True, want_calc_sum=False):
    if not isinstance(stock_array_dict, OrderedDict):
        raise TypeError('stock_array_dict must be OrderedDict')

    filter_func = (lambda day: day.change > 0) if want_up else (lambda day: day.change < 0)

    want_days = list(filter(filter_func, stock_array_dict.values()))

    if not want_calc_sum:
        return want_days

    change_sum = 0.0
    for day in want_days:
        change_sum += day.change

    return change_sum
    

    
#偏函数 partial
from functools import partial
filter_stock_up_days    = partial(filter_stock, want_up=True,  want_calc_sum=False)
filter_stock_down_days  = partial(filter_stock, want_up=False, want_calc_sum=False)
filter_stock_up_sums    = partial(filter_stock, want_up=True,  want_calc_sum=True)
filter_stock_down_sums  = partial(filter_stock, want_up=False, want_calc_sum=True)

print('所有上涨的交易日:{}'.format(list(filter_stock_up_days(stock_dict))))
print('所有下跌的交易日:{}'.format(list(filter_stock_down_days(stock_dict))))
print('所有上涨交易日的涨幅和:{}'.format(filter_stock_up_sums(stock_dict)))
print('所有下跌交易日的跌幅和:{}'.format(filter_stock_down_sums(stock_dict)))
# 所有上涨的交易日:[stock(date='20170121', price='32.56', change=0.235), stock(date='20170122', price='32.82', change=0.008)]
# 所有下跌的交易日:[stock(date='20170119', price='29.58', change=-0.019), stock(date='20170120', price='26.36', change=-0.109)]
# 所有上涨交易日的涨幅和:0.243
# 所有下跌交易日的跌幅和:-0.128

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

比特量化

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值