关键词搜索

源码搜索 ×
×

Python 常用笔记

发布2021-02-21浏览632次

详情内容

记录

http://blog.sina.com.cn/s/blog_73b339390102yoio.html

PE:市盈率 = 股价 / 每股盈利
PEG:(市盈率相对盈利增长比率/市盈增长比率)   PEG=PE/(企业年盈利增长率*100)
PB:市净率=股价 / 每股净资产
PS:市销率=股价 / 每股收入=总市值 / 销售收入
ROE:净资产收益率=报告期净利润/报告期末净资产
EPS:每股盈余=盈余 / 流通在外股数 
beta值:每股收益=期末净利润 / 期末总股本

# 投资收益率计算器
import math
年均投资收益率 = (pow(终值/本金, 1/年限) -1)*100
投资收益本息 = pow((1+预期年收益率),年限)*本金
投资目标年限 = math.log(终值/本金)/math.log(1+预期年收益率)

年化收益率 = ((终值-本金)/本金)/年限  或  利息*365/(本金*天数)
利息收益 = 本金*年化收益率*天数/365

单利终值 = 本金*(1+年利率*年限)          单利现值 = 终值/(1+年利率*年限) 
复利终值 = 本金*((1+年利率)**年限)       复利现值 = 终值/(1+年利率)**年限

等额本金月供 =(贷款本金÷还款月数)+(贷款本金-已归还本金累计额)×月利率
等额本息月供 = 本金*月利率*[(1+月利率)**(年限*12)]/[(1+月利率)**(年限*12)-1]

    时间转换

    import time
    a = '2020-03-06 19:18:00'
    a1 = time.strptime(a,'%Y-%m-%d %H:%M:%S')  #格式化str为time格式
    print(time.strftime('%Y%m%d',a1))  #格式化time格式为str
    print(time.asctime(time.localtime(time.time())))  #格式化当前时间为   Thu Apr  7 10:29:13 2016
    print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))   # 格式化成2016-03-20 11:45:39形式
    print (time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))  # 格式化成Sat Mar 28 22:24:24 2016形式
    
    a = "Sat Mar 28 22:24:24 2016"
    print (time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))) # 将格式字符串转换为时间戳
    
    import calendar
    calendar.month(2016, 1)   #输出2016年1月份的日历
    
    import pandas as pd
    pd.to_datetime('2016-03-20').strftime('%Y%m%d')  #pandas 格式化str输出
    
    from datetime import datetime,timedelta
    
    datetime.today() # 返回当前时间时分秒都为0
    now.isoweekday() # 返回的1-7代表周一--周日
    now.weekday() # 返回的0-6代表周一--到周日
    
    datetime.strptime('20150101', "%Y%m%d") # 格式化字符串成datetime格式
    
    (pd.to_datetime('20200130')+timedelta(days=3)).strftime('%Y%m%d')  #格式化后三天的日期
    
    now = datetime.now()+timedelta(days=3)
    print(now.strftime('%Y-%m-%d')) #格式化当天后三天的日期
    
      25
    • 26
    • 27
    • 28
    • 29

    列表排序

    import operator,json  
    
    aa = [{"key": "780", "A": ["01", "03", "05", "07", "09"], "T": "1"}, 
    {"key": "781", "A": ["01", "03", "05", "07", "09"], "T": "3"}, 
    {"key": "782", "A": ["01", "03", "05", "07", "09"], "T": "9"}]
    print(json.dumps(aa,indent=2, ensure_ascii=False))
    b = sorted(aa,key=operator.itemgetter('key'))  # 列表或json数据排序
    
    #虽说loads是转回json 但是像这样key是单引号不能直接转 需要先dumps
    data ="[{'a':1,'b':2,'c':3,'d':4,'e':5}]" 
    json1 = json.dumps(data)
    print(json.loads(json1))
    print(type(json1),json1)
    
    with open('222.txt','r') as f2: a = json.load(f2)
    json.dump(aa,open('111.txt','w'),indent=4)
    
    json.loads() #str转json        json.load() #读取文本str格式转json
    json.dumps() #输出成字符串    json.dump() #将json写入文本
    a = json.load(f2)
    print(json.dumps(a[0],indent=4,ensure_ascii=False))  #显示中文编码
    
    n=3
    for i in range(0,len(aa),n): b.append(aa[i:i + n])   #每三个元素一组输出一行
    
    re常用
    print(re.sub(r'[\u4e00-\u9fa5]+', ':', '1小时21分2秒'))  # 替换所有汉字为:
    print(re.findall('<li code="(.*)" class="ui-', i)) #截取字符
    
    a = ''.join(str(i)+',' for i in df1['cod'].tolist())[:-1]  #list转换str
    [i,v for i,v in enumerate(list)]
    
    a = ['e', 'a', 'u', 'o', 'i']
    a.sort()  #升序 正序
    a.sort(reverse=True)  # 降序 逆序   不能存变量
    a.sort(key= lambda x : x[1]) # 根据第二个字母排序  默认根据第一个字母排序
    
    sorted(a)  # 可存变量  保留原list  可传参数 reverse = True 降序 , reverse = False 升序(默认)
    
    sorted([[6,7,8],[2,3,4],[1,2,3]], key=lambda x: x[2]) #多维列表 根据元素排序
    
    sorted(lis,key=lambda x:cod.index(x[0])) #多维列表 根据单维列表进行指定排序  lis为多维 cod是单列表
    
    [[k,v] for k,v in dict(new).items() if k not in dict(B1).keys()]  #二维列表转化成dict,比较两个列表i[0]的差集
    
    ['别墅' if '别墅' in i else '车位' if '车位' in i else '高层' for i in a]  #列表推导示例
    [[i[0],i[2]] for i in old for v in new if i[0] == v[0] and i[2] != '0']
    
    
    d = {'lily':25, 'wangjun':22, 'John':25, 'Mary':19}
    sorted_keys = sorted(d) # 对字典而言,默认是对keys进行排序
    print(sorted_keys)
    sorted_keys1 = sorted(d, key=lambda x : x[1])
    print(d_new2)
    
    d_new = sorted(d.items(), key=lambda x: x[1], reverse=True) # 根据年龄排序,返回列表形式
    print(d_new)
    d_new = dict(d_new) # 使用内置函数把嵌套列表转换成字典
    print(d_new)
    
    sorted_values = sorted(d.values(), key=lambda x:x, reverse=False) # 排序值
    print(sorted_values)
    
    输出:
    ['John', 'Mary', 'lily', 'wangjun']
    ['wangjun', 'Mary', 'lily', 'John']
    [('lily', 25), ('John', 25), ('wangjun', 22), ('Mary', 19)]
    {'lily': 25, 'John': 25, 'wangjun': 22, 'Mary': 19}
    [19, 22, 25, 25]
    
    
    #互换dick的key和value
    d = {'lily':25, 'wangjun':22, 'John':25, 'Mary':19}
    d_new = {v:key for key,v in d.items()}
    print(d_new)
    输出:{25: 'John', 22: 'wangjun', 19: 'Mary'} 
    
    
    f.readlines()
    
    
      25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80

    编码转换

    df.to_csv('abdata.csv', mode='a', encoding='utf_8_sig') # pandas导出csv 要指定编码
    
    #python2 指定utf8
    #coding:utf-8
    import sys
    reload(sys) 
    sys.setdefaultencoding("utf-8")
    
    f.write(unicode('%s-日期    成交:%s万   成交额:%s亿'%(i[0],i[1],i[2]),"utf-8")+ '\n')  #py2写入中文也有毛病要加unicode
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    pandas操作

    from sqlalchemy import create_engine
    from datetime import datetime,timedelta
    import numpy as np
    import pandas as pd
    import tushare as ts 
    import matplotlib.pyplot as plt
    from matplotlib import colors
    from pylab import mpl  #正常显示画图时出现的中文和符号
    import time
    
    ts.set_token("123")
    pro = ts.pro_api()
    
    pd.set_option('display.unicode.ambiguous_as_wide', True)  #设置中文列名对齐
    pd.set_option('display.unicode.east_asian_width', True)  #设置列名对齐
    pd.set_option('display.max_rows',None)     #显示所有行
    pd.set_option('display.max_columns',None)  #显示所有列
    pd.set_option('expand_frame_repr', False)  #设置不换行
    pd.set_option('max_colwidth',100)   #设置显示最大字符
    np.set_printoptions(suppress=True)  # 非科学计数法
    
    mpl.rcParams['font.sans-serif']=['SimHei']
    mpl.rcParams['axes.unicode_minus']=False
    
    pd.options.mode.chained_assignment = None 
    
    %matplotlib inline  #jupyter画图用
    
      25
    • 26
    • 27

    归纳整理了一些工作中常用到的pandas使用技巧,方便更高效地实现数据分析。

    1.计算变量缺失率

    df=pd.read_csv('titanic_train.csv')
    def missing_cal(df):
        """
        df :数据集
        
        return:每个变量的缺失率
        """
        missing_series = df.isnull().sum()/df.shape[0]
        missing_df = pd.DataFrame(missing_series).reset_index()
        missing_df = missing_df.rename(columns={'index':'col',
                                                0:'missing_pct'})
        missing_df = missing_df.sort_values('missing_pct',ascending=False).reset_index(drop=True)
        return missing_df
    missing_cal(df)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    如果需要计算样本的缺失率分布,只要加上参数axis=1.

    2.获取分组里最大值所在的行方法
    分为分组中有重复值和无重复值两种。无重复值的情况。

    df = pd.DataFrame({'Sp':['a','b','c','d','e','f'], 'Mt':['s1', 's1', 's2','s2','s2','s3'], 'Value':[1,2,3,4,5,6], 'Count':[3,2,5,10,10,6]})
    df
    df.iloc[df.groupby(['Mt']).apply(lambda x: x['Count'].idxmax())]
    
    • 1
    • 2
    • 3

    先按Mt列进行分组,然后对分组之后的数据框使用idxmax函数取出Count最大值所在的列,再用iloc位置索引将行取出。有重复值的情况

    df["rank"] = df.groupby("ID")["score"].rank(method="min", ascending=False).astype(np.int64)
    df[df["rank"] == 1][["ID", "class"]]
    
    • 1
    • 2

    对ID进行分组之后再对分数应用rank函数,分数相同的情况会赋予相同的排名,然后取出排名为1的数据。

    3.多列合并为一行

    df = pd.DataFrame({'id_part':['a','b','c','d'], 'pred':[0.1,0.2,0.3,0.4], 'pred_class':['women','man','cat','dog'], 'v_id':['d1','d2','d3','d1']})
    df.groupby(['v_id']).agg({'pred_class': [', '.join],'pred': lambda x: list(x),
    'id_part': 'first'}).reset_index()
    
    • 1
    • 2
    • 3

    4.删除包含特定字符串所在的行

    df = pd.DataFrame({'a':[1,2,3,4], 'b':['s1', 'exp_s2', 's3','exps4'], 'c':[5,6,7,8], 'd':[3,2,5,10]})
    df[df['b'].str.contains('exp')]
    
    • 1
    • 2

    5.组内排序

    df = pd.DataFrame([['A',1],['A',3],['A',2],['B',5],['B',9]], columns = ['name','score'])
    介绍两种高效地组内排序的方法。
    df.sort_values(['name','score'], ascending = [True,False])
    df.groupby('name').apply(lambda x: x.sort_values('score', ascending=False)).reset_index(drop=True)
    
    • 1
    • 2
    • 3
    • 4

    6.选择特定类型的列

    drinks = pd.read_csv('data/drinks.csv')
    # 选择所有数值型的列
    drinks.select_dtypes(include=['number']).head()
    # 选择所有字符型的列
    drinks.select_dtypes(include=['object']).head()
    drinks.select_dtypes(include=['number','object','category','datetime']).head()
    # 用 exclude 关键字排除指定的数据类型
    drinks.select_dtypes(exclude=['number']).head()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    7.字符串转换为数值

    df = pd.DataFrame({'列1':['1.1','2.2','3.3'],
                      '列2':['4.4','5.5','6.6'],
                      '列3':['7.7','8.8','-']})
    df
    df.astype({'列1':'float','列2':'float'}).dtypes
    
    • 1
    • 2
    • 3
    • 4
    • 5

    用这种方式转换第三列会出错,因为这列里包含一个代表 0 的下划线,pandas 无法自动判断这个下划线。为了解决这个问题,可以使用 to_numeric() 函数来处理第三列,让 pandas 把任意无效输入转为 NaN。

    df = df.apply(pd.to_numeric, errors='coerce').fillna(0)
    
    • 1

    8.优化 DataFrame 对内存的占用
    方法一:只读取切实所python基础教程需的列,使用usecols参数

    cols = ['beer_servings','continent']
    small_drinks = pd.read_csv('data/drinks.csv', usecols=cols)
    
    • 1
    • 2

    方法二:把包含类别型数据的 object 列转换为 Category 数据类型,通过指定 dtype 参数实现。

    dtypes ={'continent':'category'}
    smaller_drinks = pd.read_csv('data/drinks.csv',usecols=cols, dtype=dtypes)
    
    • 1
    • 2

    9.根据最大的类别筛选 DataFrame

    movies = pd.read_csv('data/imdb_1000.csv')
    counts = movies.genre.value_counts()
    movies[movies.genre.isin(counts.nlargest(3).index)].head()
    
    • 1
    • 2
    • 3

    10.把字符串分割为多列

    df = pd.DataFrame({'姓名':['张 三','李 四','王 五'],
                       '所在地':['北京-东城区','上海-黄浦区','广州-白云区']})
    df
    df.姓名.str.split(' ', expand=True)
    
    • 1
    • 2
    • 3
    • 4

    11.把 Series 里的列表转换为 DataFrame

    df = pd.DataFrame({'列1':['a','b','c'],'列2':[[10,20], [20,30], [30,40]]})
    df
    df_new = df.2.apply(pd.Series)
    pd.concat([df,df_new], axis='columns')
    
    • 1
    • 2
    • 3
    • 4

    12.用多个函数聚合

    orders = pd.read_csv('data/chipotle.tsv', sep='\t')
    orders.groupby('order_id').item_price.agg(['sum','count']).head()
    
    • 1
    • 2

    13.分组聚合

    import pandas as pd
    df = pd.DataFrame({'key1':['a', 'a', 'b', 'b', 'a'],
        'key2':['one', 'two', 'one', 'two', 'one'],
        'data1':np.random.randn(5),
         'data2':np.random.randn(5)})
    df
    
    for name, group in df.groupby('key1'):
        print(name)
        print(group)
    
    dict(list(df.groupby('key1')))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    通过字典或Series进行分组

    people = pd.DataFrame(np.random.randn(5, 5),
         columns=['a', 'b', 'c', 'd', 'e'],
         index=['Joe', 'Steve', 'Wes', 'Jim', 'Travis'])
    mapping = {'a':'red', 'b':'red', 'c':'blue',
         'd':'blue', 'e':'red', 'f':'orange'}
    by_column = people.groupby(mapping, axis=1)
    by_column.sum()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    df['aa'].astype('float')  #转换整列格式
    df.reset_index(drop=True)  #重置index索引 并删除原索引
    dfs.drop_duplicates() #去除完全相同的行保留第一行
    .loc['a1']#根据index获取行    .iloc[0].name #根据行号获取行的某个值  aa.loc[:,'比_1':]获取所有行和指定列
    # loc和iloc 可以更换单行、单列、多行、多列的值
    df1.loc[0,'age']=25      # 思路:先用loc找到要更改的值,再用赋值(=)的方法实现更换值
    df1.iloc[0,2]=25         # iloc:用索引位置来查找
    .drop_duplicates().sort_values(by=['trade_date'])  #删除重复值并排序
    
    # at 、iat只能更换单个值
    df1.at[0,'age']=25      # iat 用来取某个单值,参数只能用数字索引
    df1.iat[0,2]=25         # at 用来取某个单值,参数只能用index和columns索引名称
    
    df.columns = ['c','b']  #修改索引名
    df.rename(columns={'a':'c'},inplace=True) #修改索引名
    
    #pivot()和unstack()实现行转列
    dfcod = counts[['cod','key','日期1','日期2']].set_index(['key','日期1','日期2','cod']).unstack()
    df1 , df2 = df[['日期1','日期2','key']] , df.pivot('日期2','cod',v)
    
    #行转列 列转行参考
    https://www.cnblogs.com/leohahah/p/9778304.html
    
    #新增一行 用append 但必须要得先创建DataFrame才行
    df1=df1.append(new,ignore_index=True)   # ignore_index=True,表示不按原来的索引,从0开始自动递增
    
    #新增一列
    tabsdetail['SH'] = sh.append([sh,sh,sh]).tolist()  #sh是Series
    tabs.insert(0, '总金额', [m,m*2,m*3,m*4],allow_duplicates=True)  #指定位置添加一列
    
    np.array(df0[['name','key']]).tolist()  #dataframe转化list
    
    dfdata = pd.DataFrame()
    dfdata  = dfdata.append(df1,ignore_index=True) #pandas append必须存入变量 否则不生效
    
    pd.DataFrame([[1,2,3],[1,2,3]],columns=['a','b','c'],index=df0.index)  #创建dataframe
    df0 = pd.DataFrame({'id':[3,4,5,6,7,3,4,5],
      'name':[10.54,11.11,12.80,10.05,11.21,10.98,11.12,10.55]},
      index=('a1','a2','a3','a4','a5','a6','a7','a8'))
    
    df0.loc[df0['id'] == 3 ,'key'] = 1
    df0.loc[df0['id'] == 5 ,'key'] = 0  # 进行布尔值判断 输出符合条件 
    df0['key'] = np.where(df0['id'] == 3 ,1,0)
    
    pd.concat([df0, df1], axis=1)  #合并两个dataframe 
    df.index=pd.to_datetime(df.date)  # 将index 改为时间
    df=df.sort_index() #排序index
    df['ret']=df.close/df.close.shift(1)-1   # .shift(1) 获取下一个 .shift(-1) 获取上一个
    
    data.sort_values(by=['标记','时间'],ascending=[False,True])  #多列排序指定升降序
    
    df['当天'].fillna(method='ffill',inplace=True)  #根据一列nan值填充上一个不为nan的值
    
    df['a'] = (df_new.ret+1.0).cumprod()  #计算当前值并累计连乘   .cumsum()累积连加
    
    df1['ret'].diff()   # 比较上一值与当前值的差
    [i for i in df["close"].rolling(k).mean()]   # 移动窗口list的均值
    df['c'].rolling(window=10, min_periods=1, center=False).mean()  #Series中计算均值
    
    #dataframe行转列 - 只能根据相同列名不同行名数据转置   适合matplotlib用 单index日期画图   比如多个日期 每个日期中需要转置的行名不得重复
    df1 = df[['cod','盈亏','日期2']].pivot('日期2','cod','盈亏').rename_axis([None], axis=1)  # pivot 指定列名 行名 数据  只能固定这三个参数
    df1 = df1.rename_axis(None, axis=1).reset_index()   # 取消第一个columns  将其拍平
    df1.index=pd.to_datetime(df1.日期2)
    
    #dataframe行转列 - 整合统计用   可以根据多个指定的index  但是set_index必须是前面列表-1的列 不然会乱 前面列表剩下的一个元素就是数据其他为index
    dfcod = counts[['cod','key','盈亏','日期2','日期1']].set_index(['key','日期1','日期2','cod']).unstack()
    dfcod.columns = [s1 +'_'+ str(s2) for (s1,s2) in dfcod.columns.tolist()]   # 将其拍平
    # dfcod.reset_index(inplace=True)   # 重置index 转成正常的dataframe
    dfcod.loc[['前10']]   # 根据key分组显示index和数据
    dfcod
    
    a1.index = a1.index.droplevel()  #删除一个多索引的index-names
    
    
    # series 根据list 判断是否存在
    df0[df0['id'].isin([3,4])]   #根据list获取列表信息
    df0[~df0['id'].isin([3,4])]  #根据list获取列表信息 取反
    
    # series 根据list 排序
    df['words'] = df['words'].astype('category')  #必须转换成这个格式
      df['words'].cat.reorder_categories([1,2,3], inplace=True)  # list长度相等用这个
      df['words'].cat.set_categories([1,2,3], inplace=True) # list多 用这个
      df['words'].cat.set_categories([1,2,3], inplace=True)   # list少  用这个
    df.sort_values('words', inplace=True)
    
    #df.fillna(method='bfill', inplace=True) 处理填充缺失值  inplace 是原列修改  ffill 前一个  bfill 下一个  limit=2 填充两个
    
    
    #pandas 读写mysql 
    
    from sqlalchemy 
    import create_engine 
    mysq = create_engine('mysql+pymysql://root:mysql.123@localhost/abdata?charset=utf8') 
    df.to_sql('coun',mysq,if_exists='append',index=False) # 追加数据 
    df.to_sql('counts',mysq,if_exists='replace',index=False) #删除并写入表 
    df = pd.read_sql_query('select * from cod1',mysq) # 查询mysql表 #pymysql读写mysql 
    
    import pymysql 
    conn = pymysql.connect('127.0.0.1', 'root', 'mysql.123', 'data',charset='utf8') 
    cur = conn.cursor() 
    sql1 = "SELECT * from (SELECT * from data1 ORDER BY id DESC LIMIT %s ) aa order by id" %sum cur.execute(sql1) 
    c1 = cur.fetchall() #读取mysql 
    conn.commit() #写入mysql 
     
    cur.close() 
    conn.close()
    
    
    
      25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108

    DataFrame样式设置

    
    def show(v):
    col = 'black' if v > 0 else 'green'
    return 'color:%s'%col
    
    def background_gradient(s, m, M, cmap='PuBu', low=0, high=0.8):
    rng = M - m
    norm = colors.Normalize(m - (rng * low),M + (rng * high))
    normed = norm(s.values)
    c = [colors.rgb2hex(x) for x in plt.cm.get_cmap(cmap)(normed)]
    return ['" style="color: rgb(128, 0, 0);">' % color for color in c]
    
    def highlight_max(s,m):
    is_max = s == m
    return ['" style="color: rgb(128, 0, 0);">' if v else '' for v in is_max]
    
    
    tabs.style.applymap(show).background_gradient(cmap='Reds',axis = 1,low = 0,high = 1,subset = set1).\
    apply(background_gradient,cmap='Purples',m=tabs[set2].min().min(),M=tabs[set2].max().max(),low=0,high=1,subset = set2).\
    apply(highlight_max,m=tabs[set2].max().max()).background_gradient(cmap='Wistia',axis = 1,subset=['总金额'])
    
    accdeteil.style.applymap(show).background_gradient(cmap='Reds',axis = 1,low = 0,high = 1).\
    background_gradient(cmap='Reds',axis = 1,low = 0,high = 1 ,subset=set2).\
    background_gradient(cmap='Purples',axis = 1,low = 0,high = 1,subset = pd.IndexSlice['前10',:'9']).\
    background_gradient(cmap='Purples',axis = 1,low = 0,high = 1,subset = pd.IndexSlice['前20',:'9']).\
    background_gradient(cmap='Purples',axis = 1,low = 0,high = 1,subset = pd.IndexSlice['前05','1_':]).\
    background_gradient(cmap='Purples',axis = 1,low = 0,high = 1,subset = pd.IndexSlice['前15','1_':]).\
    background_gradient(cmap='GnBu',axis = 0,low = 0,high = 1 ,subset=['SH_']).\
    apply(highlight_max,m=tabs[set2].max().max())
    
    
    #可参考
    https://blog.csdn.net/xiaodongxiexie/article/details/71202279
    
    #颜色样式
    https://matplotlib.org/tutorials/colors/colormaps.html
    
    
     
    
      25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    pandas作图

    
    import matplotlib.pyplot as plt
    
    ax1 = df1[['策略净值','指数净值']].astype(float).plot(figsize=(15,8))  #dataframe折线图
    ax1 = ax1.axhline(y=1,ls=":",c="r"),ax1.legend(loc = 'upper right')   #标记0线和指定图例位置
    plt.title('策略简单回测%s'%x,size=15)
    plt.xlabel('')
    
    for i in range(len(df1)):
        if df1['当天仓位'][i]==0 and df1['当天仓位'].shift(-1)[i]==1:
            plt.annotate('买',xy=(df1.index[i],df1.策略净值[i]),arrowprops=dict(facecolor='r',shrink=0.05))   #标记买卖点
        if df1['当天仓位'][i]==0 and df1['当天仓位'].shift(1)[i]==1:
            plt.annotate('卖',xy=(df1.index[i],df1.策略净值[i]),arrowprops=dict(facecolor='g',shrink=0.1))
    
    bbox = dict(boxstyle="round", fc="w", ec="0.5", alpha=0.9)  #指定文字边框样式
    t = f'累计收益率:策略{TA1}%,指数{TA2}%;\n年化收益率:策略{AR1}%,指数{AR2}%;'+\
    f'\n最大回撤:  策略{MD1}%,指数{MD2}%;\n策略alpha: {round(alpha,2)},策略beta:{round(beta,2)}; \n夏普比率:  {S}'
    plt.text(df1.index[0], df1['指数净值'].min(),text,size=13,bbox=bbox)   #指定位置加文字框
    ax=plt.gca()   #设置图形样式
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    plt.show()
    
    
    

      爬虫

      
      from bs4 import BeautifulSoup
      import requests
      headers = {
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
          }
      
      htm = requests.get(url=url,headers=headers,timeout=30,stream=False).text
      soup = BeautifulSoup(htm, 'html.parser')
      txt = soup.find_all('div', class_='lax-s')
      #txt = soup.find('div', class_='qi').children
      
      
      #etree方式获取   原文  https://mp.weixin.qq.com/s/c2Sg_LVTjOokePY2lxCGSA
      import requests
      import pandas as pd
      from pprint import pprint
      from lxml import etree
      import time
      import warnings
      warnings.filterwarnings("ignore")
      
      for i in range(1,15):
          print("正在爬取第" + str(i) + "页的数据")
          url = "https://search.51job.com/list/000000,000000,0000,00,9,99,%25E6%2595%25B0%25E6%258D%25AE,2,"+str(i)+'.html?'
          headers = {
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
          }
          web = requests.get(url, headers=headers)
          web.encoding = "gbk"
          dom = etree.HTML(web.text)
          #print(etree.tostring(dom, encoding="utf-8", pretty_print=True).decode("utf-8")) #打印整个html 不能直接print
          # 1、岗位名称
          job_name = dom.xpath('//div[@class="dw_table"]/div[@class="el"]//p/span/a[@target="_blank"]/@title')
          # 2、公司名称
          company_name = dom.xpath('//div[@class="dw_table"]/div[@class="el"]/span[@class="t2"]/a[@target="_blank"]/@title')
          # 3、工作地点
          address = dom.xpath('//div[@class="dw_table"]/div[@class="el"]/span[@class="t3"]/text()')
          # 4、工资:工资这一列有空值,为了保证数据框的一致性。采取以下方式进行数据的获取
          salary_mid = dom.xpath('//div[@class="dw_table"]/div[@class="el"]/span[@class="t4"]')
          salary = [i.text for i in salary_mid]  #这里None也占一个元素 保持长度一致
          # 5、发布日期
          release_time = dom.xpath('//div[@class="dw_table"]/div[@class="el"]/span[@class="t5"]/text()')
          #----------------------------------------------------------------------------------------------#
          # 下面获取二级网址的信息。为了获取二级网址的信息,首先需要获取二级网址的url
          # 6、获取二级网址url
          deep_url = dom.xpath('//div[@class="dw_table"]/div[@class="el"]//p/span/a[@target="_blank"]/@href')
          RandomAll = []
          JobDescribe = []
          CompanyType = []
          CompanySize = []
          Industry = []
          for i in range(len(deep_url)):
              web_test = requests.get(deep_url[i], headers=headers)
              web_test.encoding = "gbk"
              dom_test = etree.HTML(web_test.text)
              # 7、爬取经验、学历信息,先合在一个字段里面,以后再做数据清洗。命名为random_all
              random_all = dom_test.xpath('//div[@class="tHeader tHjob"]//div[@class="cn"]/p[@class="msg ltype"]/text()')
              # 8、岗位描述性息
              job_describe = dom_test.xpath('//div[@class="tBorderTop_box"]//div[@class="bmsg job_msg inbox"]/p/text()')
              # 9、公司类型
              company_type = dom_test.xpath('//div[@class="tCompany_sidebar"]//div[@class="com_tag"]/p[1]/@title')
              # 10、公司规模(人数)
              company_size = dom_test.xpath('//div[@class="tCompany_sidebar"]//div[@class="com_tag"]/p[2]/@title')
              # 11、所属行业(公司)
              industry = dom_test.xpath('//div[@class="tCompany_sidebar"]//div[@class="com_tag"]/p[3]/@title')
              # 将上述信息保存到各自的列表中
              RandomAll.append(random_all)
              JobDescribe.append(job_describe)
              CompanyType.append(company_type)
              CompanySize.append(company_size)
              Industry.append(industry)
              # 为了反爬,设置睡眠时间
              time.sleep(1)
          # 由于我们需要爬取很多页,为了防止最后一次性保存所有数据出现的错误,因此,我们每获取一夜的数据,就进行一次数据存取。
          df = pd.DataFrame()
          df["岗位名称"] = job_name
          df["公司名称"] = company_name
          df["工作地点"] = address
          df["工资"] = salary
          df["发布日期"] = release_time
          df["经验、学历"] = RandomAll
          df["公司类型"] = CompanyType
          df["公司规模"] = CompanySize
          df["所属行业"] = Industry
          df["岗位描述"] = JobDescribe
          # 这里在写出过程中,有可能会写入失败,为了解决这个问题,我们使用异常处理。
          try:
              df.to_csv("job_info.csv", mode="a+", header=None, index=None, encoding="gbk")
          except:
              print("当页数据写入失败")
          time.sleep(1)
      print("完毕")
      
      
      
        25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      • 49
      • 50
      • 51
      • 52
      • 53
      • 54
      • 55
      • 56
      • 57
      • 58
      • 59
      • 60
      • 61
      • 62
      • 63
      • 64
      • 65
      • 66
      • 67
      • 68
      • 69
      • 70
      • 71
      • 72
      • 73
      • 74
      • 75
      • 76
      • 77
      • 78
      • 79
      • 80
      • 81
      • 82
      • 83
      • 84
      • 85
      • 86
      • 87
      • 88
      • 89
      • 90
      • 91
      • 92
      • 93
      • 94
      • 95

      OCR图片识别

      
      #需要安装 tesseract-ocr(需要环境变量) 、chi_sim.traineddata 、 pytesseract-0.2.4 
      
      from PIL import Image
      import pytesseract,os,re
      
      png = r'D:\123\111.png'
      pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files (x86)\Tesseract-OCR\tesseract.exe'
      img = Image.open(png)
      tim = os.stat(png).st_mtime
      img1 = img.size
      aa = pytesseract.image_to_string(img, lang='chi_sim')
      print(img1,tim)
      print(aa)
      
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16

      webdriver自动化测试

      
      #需要安装 chromedriver-v69 、ChromeSetup_64_69.exe 
      
      from selenium import webdriver
      from selenium.webdriver.common.keys import Keys
      
      
      try:
          driver = webdriver.Chrome()
          driver.get("http://user/login")
          time.sleep(1)
      
          driver.find_element_by_id('username').send_keys('123123')
          driver.find_element_by_id('password').send_keys('123123')
          driver.find_element_by_id('login').click()
          time.sleep(2)
      
          driver.find_element_by_xpath('//*[@id="header"]/div[7]/div/div[1]/ul/li[4]/a').click()
          time.sleep(2)
          driver.find_elements_by_class_name('content')[2].click()
          time.sleep(2)
      
          s1 = driver.find_element_by_class_name('i1').text
          s2 = s1[3:6]
          s3 = driver.find_element_by_id('pre-kanjiang').text
          s4 = driver.find_element_by_xpath('//*[@id="money"]/strong').text
          s5 = driver.find_element_by_xpath('//*[@id="money"]/em').text
          print('key=', s2, 'time=', s3, s5 + '=', s4)
          fs.write('key=' + s2 + '\n' + 'time=' + s3 + '\n' + s5 + '=' + s4 + '\n')
          time.sleep(2)
      
          if int(s2) == int(s.get('key')):
              elements = driver.find_elements_by_class_name('code')
      
              if 'A' in s.keys():
                  data_values = s.get('A')
                  for i in data_values:
                      a_button_index = int(i) - 1
                      elements[a_button_index].click()
                      print('a_button_index = ', a_button_index)
                      fs.write('a_button_index = ' + str(a_button_index) + '\n')
              if 'B' in s.keys():
                  data_values = s.get('B')
                  for j in data_values:
                      b_button_index = int(j) + 9
                      elements[b_button_index].click()
                      print('b_button_index = ', b_button_index)
                      fs.write('b_button_index = ' + str(b_button_index) + '\n')
              if 'C' in s.keys():
                  data_values = s.get('C')
                  for k in data_values:
                      c_button_index = int(k) + 19
                      elements[c_button_index].click()
                      print('c_button_index = ', c_button_index)
                      fs.write('c_button_index = ' + str(c_button_index) + '\n')
      
              time.sleep(1)
              driver.find_elements_by_name('danwei')[1].click()
              driver.find_element_by_class_name('txt').clear()
              driver.find_element_by_class_name('txt').send_keys(int(s.get('T')) * 1)
              driver.find_element_by_class_name('tztj-hover').click()
              time.sleep(2)
              driver.find_element_by_class_name('tz-true-hover').click()
      
              time.sleep(2)
              driver.find_element_by_xpath("/html/body/div[2]/div[3]/div/button[1]").send_keys(Keys.ENTER)
              time.sleep(2)
              driver.quit()
      
      except Exception as e:
          print(e)
      
      
      
      自动点击
      
      url = "https://1111"
      
      chromeOptions = webdriver.ChromeOptions()
      chromeOptions.add_argument('User-Agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36"')
      chromeOptions.add_argument('lang=zh_CN.UTF-8')
      driver = webdriver.Chrome(chrome_options=chromeOptions)
      driver.get(url)
      driver.delete_all_cookies() #清空cookie
      driver.add_cookie({'name':'JSESSIONID','value':'D11197B'})
      time.sleep(1)
      driver.refresh() #刷新页面
      time.sleep(1)
      
      driver.switch_to_frame(0)  #进入第一个frame
      # driver.switch_to.default_content()  #回退frame
      
      drilis = driver.find_elements_by_class_name('ui-question-options-order')  #获取所有选项的元素
      oplis = [drilis[i:i + 4] for i in range(0,len(drilis),4)] # 每个ABCD一组
      print(oplis)
      
      for i,v in zip(oplis,idlis):
          if v == 'A':i[0].click()
          elif v == 'B':i[1].click()
          elif v == 'C':i[2].click()
          elif v == 'D':i[3].click()
          time.sleep(0.1)
      
        25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      • 49
      • 50
      • 51
      • 52
      • 53
      • 54
      • 55
      • 56
      • 57
      • 58
      • 59
      • 60
      • 61
      • 62
      • 63
      • 64
      • 65
      • 66
      • 67
      • 68
      • 69
      • 70
      • 71
      • 72
      • 73
      • 74
      • 75
      • 76
      • 77
      • 78
      • 79
      • 80
      • 81
      • 82
      • 83
      • 84
      • 85
      • 86
      • 87
      • 88
      • 89
      • 90
      • 91
      • 92
      • 93
      • 94
      • 95
      • 96
      • 97
      • 98
      • 99
      • 100
      • 101
      • 102

      cs客户端自动化测试

      import os,sys,time
      import pywinauto
      import pywinauto.clipboard
      import pywinauto.application
      import win32clipboard as wincb
      import win32con
      
      
      def winmax(): #窗口最大化
          if main_window.get_show_state() != 3:
              main_window.maximize()
          main_window.set_focus()
      
      def winmin(): #窗口最小化
          if main_window.GetShowState() != 2:
              main_window.Minimize()
      
      def closepopup():  #关闭弹窗
          popup_hwnd = main_window.PopupWindow()
          if popup_hwnd:
              popup_window = app.window_(handle=popup_hwnd)
              popup_window.SetFocus()
              popup_window.Button.Click()
              return True
          return False
      
      def pos():  #获取持仓并刷新复制到剪切板
          dialog_window.CCustomTabCtrl.ClickInput(coords=(30, 8))  #点击持仓
          dialog_window.Button5.click()
          time.sleep(0.5)
          dialog_window.Button5.click()
          # time.sleep(0.2)
          # dialog_window.CVirtualGridCtrl.RightClick(coords=(100, 70))  # 右击持仓
          # main_window.TypeKeys('C')   #如果能复制了 就把这些打开
      
      def copypos():  #获取剪切板信息
          wincb.OpenClipboard()
          t = wincb.GetClipboardData(win32con.CF_TEXT)
          wincb.CloseClipboard()
          return t
      
      def copyposition():  #导出持仓并读取
          dialog_window.CVirtualGridCtrl.RightClick(coords=(100, 70))  # 右击持仓
          main_window.TypeKeys('S')
          time.sleep(0.1)
          closepopup()
          closepopup()
          with open('C:/Users/Administrator/Desktop/table.xls','r') as f:
              return [[i.split('\t')[1],i.split('\t')[3],i.split('\t')[4]] for i in f.readlines()[1:]]
      
      def order(x):  #B是买  S是卖   开始下单
          dialog_window.TypeKeys("{F6}")
          if x == 'B':
              for i in Blis:
                  # dialog_window.window(title_re='重填').click()
                  time.sleep(0.1)
                  dialog_window.Edit1.set_focus()
                  dialog_window.Edit1.set_edit_text(i[0])
                  dialog_window.Edit3.set_edit_text(i[1])
                  time.sleep(0.2)
                  dialog_window.Button1.click()
          if x == 'S':
              for i in Slis:
                  time.sleep(0.1)
                  dialog_window.Edit4.set_focus()
                  dialog_window.Edit4.set_edit_text(i[0])
                  dialog_window.Edit6.set_edit_text(i[1])
                  time.sleep(0.2)
                  dialog_window.Button2.click()
      
      def cancel(x): #撤单  B:撤买  S:撤卖  all:全撤
          dialog_window.CCustomTabCtrl.ClickInput(coords=(140, 8))  #点击委托
          try:
              dialog_window.Button6.Click()
              time.sleep(0.1)
              dialog_window.Button6.Click()
          except Exception as e:
              pass
          if x == 'B':
              dialog_window.Button8.Click()
          if x == 'S':
              dialog_window.Button9.Click()
          if x == 'all':
              dialog_window.Button7.Click()
          time.sleep(0.1)
          closepopup()
      
      def BSlist(x): #返回买卖剩余量  B是买  S是卖
          global Blis
          global Slis
          pos()         #可以复制了就打开old
          # old = [[i.split('\t')[1],i.split('\t')[3],i.split('\t')[4]] for i in copypos().decode("gb2312").split('\r\n')[1:]]
          old = copyposition()
          new = [[i[0],'0'] for i in Slis if int(i[1]) > 0 ]+Blis
          if x == 'B':
              B1 = [[v[0],str(int(i[1])-int(v[1]))] for i in [i for i in new if i[1] != '0'] for v in old if i[0] == v[0]]
              B2 = [[k,v] for k,v in dict([i for i in new if i[1] != '0']).items() if k not in dict(B1).keys()]
              Blis = [i for i in B1 if i[1] != '0']+B2
              return Blis
          if x == 'S':
              Slis = [[i[0],i[2]] for i in old for v in [i for i in new if i[1] == '0'] if i[0] == v[0] and i[2] != '0']
              return Slis
      
      
      if __name__ == '__main__':
          files = [i for i in os.listdir('D:/abdata/csv/') if 'cod' in i]
      
          Blis = []
          Slis = []
          with open('D:/abdata/csv/'+sorted(files)[-1],'r',encoding='utf-8') as f:
              for i in f:
                  i = i.strip().split(',')
                  if i[4] == '0' and int(i[2]) >0:Blis.append([i[0],i[2]])
                  if i[4] == '1' and int(i[2]) >0:Slis.append([i[0],i[2]])
      
          '''
          order(x):  # 需要传参  B是买  S是卖 
          cancel(x): # 撤单  B:撤买  S:撤卖  all:全撤
          BSlist(x): # 返回买卖剩余量  B是买  S是卖
          winmax():  # 窗口最大化                    winmin():  # 窗口最小化
          pos():     # 获取持仓并刷新复制到剪切板        copypos():  # 获取剪切板信息
          closepopup():  #关闭弹窗                    copyposition():  #导出持仓并读取
          '''
      
          title = '网上股票交易系统5.0'
          app = pywinauto.application.Application()
          app.connect(title=title)
          top_hwnd = pywinauto.findwindows.find_window(title=title)
          dialog_hwnd = pywinauto.findwindows.find_windows(top_level_only=False, class_name=u'#32770', parent=top_hwnd)[0]
          wanted_hwnds = pywinauto.findwindows.find_windows(top_level_only=False, parent=dialog_hwnd)
          main_window = app.window(handle=top_hwnd)
          dialog_window = app.window(handle=dialog_hwnd)
          winmax()  #窗口最大
          # pos()  #获取复制持仓
      
          # old = [[i.split('\t')[1],i.split('\t')[3]] for i in copypos().decode("gb2312").split('\r\n')[1:]]
          # new = [[i[0],'0'] for i in Slis if int(i[1]) > 0 ]+Blis
      
          B = 1
          S = 1
      
          while S > 0 :
              closepopup()
              time.sleep(0.5)
              # pos()  #获取复制持仓
              Slis = BSlist('S')
              S = len(Slis)
              if S > 0:
                  closepopup()
                  order('S')
                  closepopup()
                  time.sleep(2)
                  cancel('all')
                  time.sleep(2)
      
          while B > 0 :
              time.sleep(0.5)
              closepopup()
              # pos()  #获取复制持仓
              Blis = BSlist('B')
              B = len(Blis)
              if B > 0:
                  closepopup()
                  order('B')
                  closepopup()
                  time.sleep(2)
                  cancel('all')
                  time.sleep(2)
      
      
      
        25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      • 49
      • 50
      • 51
      • 52
      • 53
      • 54
      • 55
      • 56
      • 57
      • 58
      • 59
      • 60
      • 61
      • 62
      • 63
      • 64
      • 65
      • 66
      • 67
      • 68
      • 69
      • 70
      • 71
      • 72
      • 73
      • 74
      • 75
      • 76
      • 77
      • 78
      • 79
      • 80
      • 81
      • 82
      • 83
      • 84
      • 85
      • 86
      • 87
      • 88
      • 89
      • 90
      • 91
      • 92
      • 93
      • 94
      • 95
      • 96
      • 97
      • 98
      • 99
      • 100
      • 101
      • 102
      • 103
      • 104
      • 105
      • 106
      • 107
      • 108
      • 109
      • 110
      • 111
      • 112
      • 113
      • 114
      • 115
      • 116
      • 117
      • 118
      • 119
      • 120
      • 121
      • 122
      • 123
      • 124
      • 125
      • 126
      • 127
      • 128
      • 129
      • 130
      • 131
      • 132
      • 133
      • 134
      • 135
      • 136
      • 137
      • 138
      • 139
      • 140
      • 141
      • 142
      • 143
      • 144
      • 145
      • 146
      • 147
      • 148
      • 149
      • 150
      • 151
      • 152
      • 153
      • 154
      • 155
      • 156
      • 157
      • 158
      • 159
      • 160
      • 161
      • 162
      • 163
      • 164
      • 165
      • 166
      • 167
      • 168
      • 169
      • 170
      
      
      vba合并所有工作表sheet为一个
      
      
      Sub 合并当前工作簿下的所有工作表()
      Application.ScreenUpdating = False
      For j = 1 To Sheets.Count
      If Sheets(j).Name <> ActiveSheet.Name Then
      X = Range("A65536").End(xlUp).Row + 1
      Sheets(j).UsedRange.Copy Cells(X, 1) '复制内容
      End If
      Next
      Range("B1").Select  '表明从B1单元格开始复制合并的内容
      Application.ScreenUpdating = True
      MsgBox "当前工作簿下的全部工作表已经合并完毕!", vbInformation, "提示"
      End Sub
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17

      相关技术文章

      点击QQ咨询
      开通会员
      返回顶部
      ×
      微信扫码支付
      微信扫码支付
      确定支付下载
      请使用微信描二维码支付
      ×

      提示信息

      ×

      选择支付方式

      • 微信支付
      • 支付宝付款
      确定支付下载