博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python量化教程 常用函数
阅读量:5058 次
发布时间:2019-06-12

本文共 4960 字,大约阅读时间需要 16 分钟。

# -*- 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'}# 可命名元组 namedtuplefrom collections import namedtuplestock_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')]# 有序字典 OrderedDictfrom collections import OrderedDictstock_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后装入listprice_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()函数即两个相邻的价格, 求出涨跌幅度,返回外层结果listchange_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_dictstock_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        #偏函数 partialfrom functools import partialfilter_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

 

转载于:https://www.cnblogs.com/fangbei/p/9463334.html

你可能感兴趣的文章
8 -- 深入使用Spring -- 3...1 Resource实现类InputStreamResource、ByteArrayResource
查看>>
硬件笔记之Thinkpad T470P更换2K屏幕
查看>>
一个关于vue+mysql+express的全栈项目(六)------ 聊天模型的设计
查看>>
【知识库】-数据库_MySQL 的七种 join
查看>>
.net 写文件上传下载webservice
查看>>
noSQL数据库相关软件介绍(大数据存储时候,必须使用)
查看>>
iOS开发——缩放图片
查看>>
HTTP之URL的快捷方式
查看>>
满世界都是图论
查看>>
配置链路聚合中极小错误——失之毫厘谬以千里
查看>>
代码整洁
查看>>
蓝桥杯-分小组-java
查看>>
Java基础--面向对象编程1(类与对象)
查看>>
Android Toast
查看>>
iOS开发UI篇—Quartz2D使用(绘制基本图形)
查看>>
docker固定IP地址重启不变
查看>>
桌面图标修复||桌面图标不正常
查看>>
JavaScript基础(四)关于对象及JSON
查看>>
关于js sort排序方法
查看>>
JAVA面试常见问题之Redis篇
查看>>