Multiprocessing

最近在写一个代码,感觉要run很久,在群里问,有人建议采用multiprocessing。开始看官方文档。然而有一个程序却测试跑不出来。

# -*- coding: utf-8 -*-
"""
Created on Sun Jul 30 19:42:12 2017
multiprocessing_test
"""

import multiprocessing as mp

def f(name):
      print('hello', name)

if __name__ == '__main__':
       p = mp.Process(target=f, args=('bob',))
       p.start()
       p.join()
# 在anaconda的spyder中,一定要有这一句才ok。
# 但是在fluent python中,不需要这一句
      p.run() #output为 hello bob

#下面的程序运行正常
def f2(x):
     return x**x

if __name__ == '__main__':
     with mp.Pool(5) as p:
            print(p.map(f2, [1, 2, 3])) #output为[1, 4, 9]

Trump, Yellen

今天一位在米国的投资机构人员来拜访,大家正好相互交流一下。他对中国好像有些陌生了,而我们也正好请教一下米国市场的情况。

简要记录一下问的几个问题及他的回答。

  1. 关于Trump。
    1. 米国之前是左派和右派(知乎上有一个比较说明)之争,但无论左派和右派,代表的都是政治精英。而trump的上台,是普通民众相对精英的胜利。trump这个人就是一个商人,他没有什么立场,有的只是利益。
    2. Trump在未上台之前,是代表所谓普通民众的利益。但是他上台之后,他会考虑什么问题?经济要保持稳健(加息显然是不利于经济增长的),自己能够获得连任。从经济增长的角度看,trump显然也不太希望加息。
    3. 以前经常是一方有总统,另一方有两院。而现在总统、参议院、众议院现在都在共和党手里,2018年的中期选举马上就要来了,如果共和党还不做点成绩出来,那不是正好被民主党攻击?
    4. 关于医疗方案、减税。共和党是不太希望看到政府赤字太高的。如果医疗方案能够通过,那么这将为美国政府降低财政支出。那么,减税的方案就相对容易通过。如果医疗方案不通过,那么,减税这事情就难了,或者会采取部分减税的方式(例如对美国企业在境外的利润流入到国内降低税率)。
    5. Trump是不喜欢Yellen的,他想把Yellen换成自己更喜欢的人。但是,其实面临很多的挑战。Trump本来要提名700+人到政府的各个部门任职,但到现在,才通过了40+个,这个速度是有史以来最慢的。如果trump要换美联储主席,那么又会影响对其他人提名的任职。
  2. 利率、缩表:
    1. 美国的资产价格泡沫,增值的是谁,是那些有钱的阶级。对普通民众而言,资产价值泡沫,对他们没有什么好处,他们看到的只是更高的资产价格。高利率会损害谁?高利率会使得资产价格泡沫破灭,那些有钱的阶级当然不想看到。
    2. 关于加息。目前美国的利率相比欧洲、日本来说是高的,如果美国加息,那么资金就会流入美国。从某种意义上来说,是欧洲、日本的低利率压制了美国的加息。从经济调控的角度,是想趁有机会,先把利率调上去,这样等下一次危机来临的时候,政府和央行才会有一些可用的调控工具。
    3. 关于缩表。在美联储扩表之前,曾经有研究认为美联储的扩表使得美国的利率下降了100-200bp,而现在普遍预期美联储将在9月将进行缩表,但一些分析却认为缩表只会使得利率提升20-40bp。这难道不是一个很奇怪的事情吗?市场在90%的时候是对的,但也有10%的时候是错的。如果这次是市场错了呢?

groupby_fillna_for special columns

Well, there is no problem to merge data and fillna.

sometimes we want to fillna with groupby, more specifically, we need to fillna with different methods, some are ffill, while others are fillna(0).

the following code can deal with this situation.

# -*- coding: utf-8 -*-
“””
groupby_fillna_special columns
https://stackoverflow.com/questions/21284585
“””

import pandas as pd
from io import StringIO

# fillna with groupby
csvdata=”””
STK_ID RPT_Date sales opr_pft net_pft
002138 20130331 2.0703 0.3373 0.2829
002138 20130630 NaN NaN NaN
002138 20130930 7.4993 1.2248 1.1630
002138 20140122 NaN NaN NaN

600004 20130331 11.8429 3.0816 2.1637
600004 20130630 24.6232 6.2152 4.5135
600004 20130930 37.9673 9.2088 6.6463
600004 20140122 NaN NaN NaN

600809 20130331 27.9517 9.9426 7.5182
600809 20130630 40.6460 13.9414 9.8572
600809 20130930 53.0501 16.8081 11.8605
600809 20140122 NaN NaN NaN
“””
sio=StringIO(csvdata)

df=pd.read_csv(sio, sep=’\s+’,header=0,dtype={“STK_ID”:object,”RPT_Date”:object,
“sales”:float,’apr_pft’:float,
‘net_pft’:float})
df.set_index([‘STK_ID’,’RPT_Date’],inplace=True)

#ffill all columns with groupby
#DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs)[source]
df.groupby(level=0).apply(lambda grp: grp.fillna(method=’ffill’))

#fillnow the lastrow with groupby
def f(g):
last = len(g.values)-1
g.iloc[last,:] = g.iloc[last-1,:]
return g
df.groupby(level=0).apply(f)

# fill certain columns
df[[‘sales’,’opr_pft’]]=df.groupby(level=0)[[‘sales’,’opr_pft’]].fillna(method=’ffill’)
#or you can write as following
df[[‘sales’,’opr_pft’]]=df.groupby(level=0)[[‘sales’,’opr_pft’]].apply(lambda grp: grp.fillna(method=’ffill’))

upsampling with multiindex

I want to resampling(more specifically, upsampling) data with multiindex.

Thanks for stackoverflow, https://stackoverflow.com/questions/39737890/, I find a solution.  the code has some minor error, I have corret it.

# -*- coding: utf-8 -*-
“””
upsampling with multiindex
“””

import pandas as pd
import datetime
import numpy as np
np.random.seed(1234)

arrays = [np.sort([datetime.date(2016, 8, 31),
datetime.date(2016, 7, 31),
datetime.date(2016, 6, 30)]*5),
[‘A’, ‘B’, ‘C’, ‘D’, ‘E’]*3]
df = pd.DataFrame(np.random.randn(15, 4), index=arrays)
df.index.rename([‘date’, ‘id’], inplace=True)
print(df)

df1=df.unstack().resample(‘W-FRI’).last().ffill().stack()
print(‘\n df1:\n’,df1)

the result is as following:

                         0                    1                2                 3
date            id
2016-06-30 A 0.471435 -1.190976 1.432707 -0.312652
B -0.720589 0.887163 0.859588 -0.636524
C 0.015696 -2.242685 1.150036 0.991946
D 0.953324 -2.021255 -0.334077 0.002118
E 0.405453 0.289092 1.321158 -1.546906
2016-07-31 A -0.202646 -0.655969 0.193421 0.553439
B 1.318152 -0.469305 0.675554 -1.817027
C -0.183109 1.058969 -0.397840 0.337438
D 1.047579 1.045938 0.863717 -0.122092
E 0.124713 -0.322795 0.841675 2.390961
2016-08-31 A 0.076200 -0.566446 0.036142 -2.074978
B 0.247792 -0.897157 -0.136795 0.018289
C 0.755414 0.215269 0.841009 -1.445810
D -1.401973 -0.100918 -0.548242 -0.144620
E 0.354020 -0.035513 0.565738 1.545659

df1:
0              1                2                 3
date            id
2016-07-01 A 0.471435 -1.190976 1.432707 -0.312652
B -0.720589 0.887163 0.859588 -0.636524
C 0.015696 -2.242685 1.150036 0.991946
D 0.953324 -2.021255 -0.334077 0.002118
E 0.405453 0.289092 1.321158 -1.546906
2016-07-08 A 0.471435 -1.190976 1.432707 -0.312652
B -0.720589 0.887163 0.859588 -0.636524
C 0.015696 -2.242685 1.150036 0.991946
D 0.953324 -2.021255 -0.334077 0.002118
E 0.405453 0.289092 1.321158 -1.546906
2016-07-15 A 0.471435 -1.190976 1.432707 -0.312652
B -0.720589 0.887163 0.859588 -0.636524
C 0.015696 -2.242685 1.150036 0.991946
D 0.953324 -2.021255 -0.334077 0.002118
E 0.405453 0.289092 1.321158 -1.546906
2016-07-22 A 0.471435 -1.190976 1.432707 -0.312652
B -0.720589 0.887163 0.859588 -0.636524
C 0.015696 -2.242685 1.150036 0.991946
D 0.953324 -2.021255 -0.334077 0.002118
E 0.405453 0.289092 1.321158 -1.546906
2016-07-29 A 0.471435 -1.190976 1.432707 -0.312652
B -0.720589 0.887163 0.859588 -0.636524
C 0.015696 -2.242685 1.150036 0.991946
D 0.953324 -2.021255 -0.334077 0.002118
E 0.405453 0.289092 1.321158 -1.546906
2016-08-05 A -0.202646 -0.655969 0.193421 0.553439
B 1.318152 -0.469305 0.675554 -1.817027
C -0.183109 1.058969 -0.397840 0.337438
D 1.047579 1.045938 0.863717 -0.122092
E 0.124713 -0.322795 0.841675 2.390961
2016-08-12 A -0.202646 -0.655969 0.193421 0.553439
B 1.318152 -0.469305 0.675554 -1.817027
C -0.183109 1.058969 -0.397840 0.337438
D 1.047579 1.045938 0.863717 -0.122092
E 0.124713 -0.322795 0.841675 2.390961
2016-08-19 A -0.202646 -0.655969 0.193421 0.553439
B 1.318152 -0.469305 0.675554 -1.817027
C -0.183109 1.058969 -0.397840 0.337438
D 1.047579 1.045938 0.863717 -0.122092
E 0.124713 -0.322795 0.841675 2.390961
2016-08-26 A -0.202646 -0.655969 0.193421 0.553439
B 1.318152 -0.469305 0.675554 -1.817027
C -0.183109 1.058969 -0.397840 0.337438
D 1.047579 1.045938 0.863717 -0.122092
E 0.124713 -0.322795 0.841675 2.390961
2016-09-02 A 0.076200 -0.566446 0.036142 -2.074978
B 0.247792 -0.897157 -0.136795 0.018289
C 0.755414 0.215269 0.841009 -1.445810
D -1.401973 -0.100918 -0.548242 -0.144620
E 0.354020 -0.035513 0.565738 1.545659

read h5 and remove prefix ‘b’

h5文件是存储大数据的一种较好格式,在读取该文件的时候,有时候会有prefix ‘b’.因此,要设法去除该prefix。

# -*- coding: utf-8 -*-
import tables as tb
import pandas as pd
import numpy as np
import time

time0=time.time()
pth=’d:/download/’

# 读取交易的数据
data_trading=pth+’Trading_v01.h5′
filem=tb.open_file(data_trading,mode=’a’,driver=”H5FD_CORE”)
tb_trading=filem.get_node(where=’/’, name=’wind_data’)
df=pd.DataFrame.from_records(tb_trading[:])
time1=time.time()
print(‘\ntime on reading data: %6.3fs’ %(time1-time0))
# in python3, remove prefix ‘b’
for key in [‘Date’, ‘Code’]:
df[key] = df[key].str.decode(“utf-8”)

# the following two methods are
# method 1
#str_df = df.loc[:,[‘Date’,’Code’]]
#str_df = str_df.stack().str.decode(‘utf-8′).unstack()
#for col in str_df:
# df[col] = str_df[col]
#method 2
#df.loc[:,’Date’]=[[dt.decode(‘utf-8′)] for dt in df.loc[:,’Date’]]
#df.loc[:,’Code’]=[[cd.decode(‘utf-8′)] for cd in df.loc[:,’Code’]]

time2=time.time()
print(“\ntime on removing prefix ‘b’: %6.3fs” %(time2-time1))
print(‘\ntotal time: %6.3fs’ %(time2-time0))

运行结果如下

time on reading data: 1.508s

time on removing prefix ‘b’: 9.315s

total time: 10.823s

不知道有没有更快捷的方式。

Add new column to Pytables

h5是很好的保存文件的格式,该文件格式有一个优势是支持快速读取,但是在写入列上有些麻烦。比较好的写入新列的方式,是将新生成的数据写入到一个新的表中,然后删除原来的表。

以下代码就是实现上述功能(此后文章未加说明,均为在Windows+Python 3 上实现)

  1. # -*- coding: utf-8 -*-
  2. # read data from h5 file and add one colume, then write new data to a new file
  3. import tables as tb
  4. import pandas as pd
  5. import numpy as np
  6. import time
  7. import sys
  8. time0=time.time()
  9. pth=‘d:/download/’
  10. data_file=pth+‘data0.h5’
  11. #read data from the file
  12. filem=tb.open_file(data_file,mode=‘a’,driver=“H5FD_CORE”)
  13. df0=filem.get_node(where=‘/’,name=‘FinancialData’)
  14. df = pd.DataFrame.from_records(df0[:])
  15. df[‘UniqueorNot’]=np.where(df.duplicated(subset=[‘Date’,‘Code’]),‘Duplicated’,‘Unique’)
  16. # convert object to string, because table can not accept object
  17. def foo(atype):
  18.     if atype==np.object_:
  19.         return ‘S10’
  20.     return atype
  21. def df_dtype(df):
  22.     cols = df.columns
  23.     if  sys.version_info[0] == 2:  # python 2 needs .encode() but 3 does not
  24.         types = [(cols[i].encode(), foo(df[k].dtype.type)) for (i, k) in enumerate(cols)]
  25.     else:
  26.         types = [(cols[i], foo(df[k].dtype.type)) for (i, k) in enumerate(cols)]
  27.     dtype = np.dtype(types)
  28.     return dtype
  29. dty = df_dtype(df)
  30. # write to a new PyTables table
  31. data_file=pth+‘data1.h5’
  32. data_h5 = tb.open_file(data_file, ‘a’)
  33. # make a definiton of creating Pytables
  34. def c_table(f,tname,tdty,data):
  35.     try:
  36.         f.create_table(where=‘/’, name=tname, description=tdty)
  37. #    if the table has already been created, then do nothing
  38.     except tb.NodeError:
  39.         print(\n, tname, ‘is existing’)
  40.         pass
  41. #    get data from table
  42.     c=f.get_node(where=‘/’,name=tname)
  43. #   data can be list, and internal type is tuple
  44.     ts = [tuple(s) for s in data]
  45.     c.append(rows=ts)
  46.     c.flush()
  47. # if you do not want to save the file to csv, you can drop the following two rows.
  48. #    df = pd.DataFrame.from_records(c[:])
  49. #    df.to_csv(pth+’data1.csv’)
  50. # write new data to file
  51. namelist=[‘FinancialData’]
  52. for c in namelist:
  53.     c_table(data_h5,c,dty,df.as_matrix())
  54. #flush and close the file
  55. data_h5.flush()
  56. data_h5.close()
  57. # check the time elapsed
  58. time2=time.time()
  59. print(\n%8.4fs’ %(time2-time0))

宏观经济的书籍

ID 书名 作者 版本 出版社 出版时间 ISBNID 书名 作者 版本 出版社 出版时间 ISBN

  1. Economic Principles: How the Economic Machine Works, Ray Dalio, 英文版, Bridgewater
  2. 成本冲击、通胀容忍度与宏观政策,伍戈、李斌, 中文版, 中国金融出版社, 2013年6月, 9787504968999
  3. 信用创造、货币供求与经济结构, 李斌、伍戈, 中文版, 中国金融出版社, 2014年12月, 9787504976987
  4. 货币数量、利率调控与政策转向, 伍戈、李斌, 中文版, 中国金融出版社, 2016年1月, 9787504982858
  5. 新货币政策框架下的利率传导机制, 马骏、纪敏, 中文版, 中国金融出版社, 2016年4月,9787504984302
  6. 货币政策实施:理论、沿革与现状, Ulrich Bindseil, 中译本, 东北财经大学出版社, 2013年12月 9787565414671
  7.  货币政策理论与分析, 明明, 中文版, 中国金融出版社, 2017年3月, 9787504989000
  8. 中央银行与货币供给(第二版), 盛松成 ,中文版, 中国金融出版社 ,2016年8月 ,9787504986214
  9. 汇率的本质, 管涛, 中文版, 中信出版社, 2016年8月, 9787508665245
  10. 经济指标解读:洞悉未来经济发展趋势和投资机会, Bernard Baumohl 伯纳德·鲍莫尔, 中译本, 中国人民大学出版社, 2005年10月, 9787300108506
  11. 我在高盛的经济预测法, Joseph H. Ellis约瑟夫 H.埃利斯, 中文版, 机械工业出版社, 2011年6月, 9787111347682
  12. 聪明投资:如何利用经济枯荣循环获利, 乔治·达格尼诺, 中译本, 山西人民出版社, 2011年1月, 9787203071129
  13. 解读中国经济指标:在数字中锁定投资机会, Tom Orlik,中译本,中国经济出版社,2012年3月,9787513614443
  14. 逃不开的经济周期:历史,理论与投资现实, Lars Tvede拉斯·特维德, 中译本, 中信出版社, 2012年11月,9787508635217
  15. 经济周期谁也逃不开:中国企业怎么办,李嘉华,中文版,人民邮电出版社,2013年7月, 9787115323293
  16. 经济周期模型 Robert E.Lucas,Jr 中译本 中国人民大学出版社 2013年1月 9787300169446
  17. 渐行渐远的红利:寻找中国新平衡, 彭文生, 中文版, 社会科学文献出版社, 2013年4月, 9787509744246
  18. 渐行渐近的金融周期, 彭文生, 中文版, 中信出版集团, 2017年6月, 9787508675909
  19. 经济运行的逻辑,高善文,中文版,中国人民大学出版社,2013年6月,9787300173443
  20. 在周期的拐点上–从数据看中国经济的波动,高善文,中文版,中国发展出版社,2006年1月,9787800878725
  21. 透视繁荣–资产重估深处的忧虑,高善文,中文版,中国物价出版社,2007年11月, 9787509202104
  22. 经济数据背后的财富密码, 李迅雷, 中文版, 经济科学出版社, 2017年6月,9787514181685
  23. 预测背后的逻辑,鲁政委,中文版,机械工业出版社,2012年9月,9787111393504
  24. 大势研判:经济、政策与资本市场,任泽平,中文版,中信出版社,2016年7月,9787508662091
  25. 中国PMI研究与实践,中国物流与采购联合会, 中文版, 中国财富出版社, 2012年12月, 9787504745347
  26. 经济学的思维方式(影印第12版), 保罗·海恩、彼得·勃特克、大卫·普雷契特科, 英文版, 世界图书出版公司·后浪出版公司, 2012年10月, 9787510049927
  27. 经济学300年(上、下), 何正斌, 中文版, 湖南科技出版社, 2009年6月, 9787535748256
  28. 正常的终结:理解世界经济新常态, [美]詹姆斯·K. 加尔布雷斯, 中译本, 中信出版社, 2017年2月, 9787508669014
  29. 投资交易笔记:2002-2010年中国债券市场研究回眸, 董德志, 中文版, 经济科学出版社 ,2011年6月, 9787514106701 
  30. 投资交易笔记续:2011-2015年中国债券市场研究回眸, 董德志, 中文版, 经济科学出版社, 2016年9月, 9787514172331