In [1]:
from __future__ import print_function
from __future__ import division
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
%matplotlib inline
sns.set_context(rc={'figure.figsize': (14, 7) } )
figzize_me = figsize =(14, 7)
# import warnings; warnings.simplefilter('ignore')
import sys
import os
# 使用insert 0即只使用github,避免交叉使用了pip安装的abupy,导致的版本不一致问题
sys.path.insert(0, os.path.abspath('../'))
import abupy
In [2]:
arr1 = np.random.rand(10000)
arr2 = np.random.rand(10000)
corr = np.cov(arr1, arr2) / np.std(arr1) * np.std(arr2)
corr
Out[2]:
In [3]:
corr[0, 1]
Out[3]:
In [4]:
np.corrcoef(arr1, arr2)[0, 1]
Out[4]:
In [5]:
arr1 = np.random.rand(10000)
arr2 = arr1 + np.random.normal(0, .2, 10000)
np.corrcoef(arr1, arr2)[0, 1]
Out[5]:
In [6]:
import scipy.stats as stats
demo_list = [1, 2, 10, 100, 2, 1000]
print('原始序列: ', demo_list)
print('序列的秩: ', list(stats.rankdata(demo_list)))
In [7]:
# 实现斯皮尔曼秩相关系数
def spearmanr(a, b=None, axis=0):
a, outaxis = _chk_asarray(a, axis)
ar = np.apply_along_axis(stats.rankdata, outaxis, a)
br = None
if b is not None:
b, axisout = _chk_asarray(b, axis)
br = np.apply_along_axis(stats.rankdata, axisout, b)
return np.corrcoef(ar, br, rowvar=outaxis)
def _chk_asarray(a, axis):
if axis is None:
a = np.ravel(a)
outaxis = 0
else:
a = np.asarray(a)
outaxis = axis
if a.ndim == 0:
a = np.atleast_1d(a)
return a, outaxis
In [8]:
%time spearmanr(arr1, arr2)[0, 1]
Out[8]:
In [9]:
# 注意下面的方法速度没有上述自己实现计算spearmanr相关系数的方法快,因为附加计算了pvalue
%time stats.spearmanr(arr1, arr2)
Out[9]:
相关分析默认强制使用local数据,所以本地无缓存,请先进行数据更新
所有获取的数据已经存放在百度云盘上,后面的章节使用的数据都是本节更新的数据,建议直接从云盘下载入库完毕的数据库,不需要从各个数据源再一个一个的下载数据进行入库,百度云地址如下:
csv格式美股,A股,港股,币类,期货6年日k数据 密码: gvtr
下面数据存贮格式为hdf5数据,由于hdf5文件解压后非常大,还需要区分python版本,所以如果没有足够的存贮空间 特别是python2下,建议使用csv格式的缓存文件:
mac系统python3 美股,A股,港股,币类,期货6年日k数据 密码: ecyp
mac系统python2 A股6年日k数据: 密码: sid8
mac系统python2 美股6年日k数据: 密码: uaww
windows python3 美股,A股,港股,币类,期货6年日k数据 密码: 3cwe
windows python2 A股6年日k数据: 密码: 78mb
windows python2 美股6年日k数据: 密码: 63r3
下载完毕上述数据后,hdf5解压得到df_kl.h5文件,csv解压得到csv文件夹,解压后放到下面路径下即可
In [ ]:
if abupy.env.g_is_mac_os:
!open $abupy.env.g_project_data_dir
else:
!echo $abupy.env.g_project_data_dir
如果不想通过直接下载数据文件的方式,也可下面通过切换至腾讯数据源,然后进行美股数据全市场更新:
备注:耗时操作,大概需要运行15分钟左右,可以在做其它事情的时候运行
In [10]:
def tx_us():
from abupy import EMarketSourceType, EDataCacheType, EMarketTargetType
abupy.env.g_market_source = EMarketSourceType.E_MARKET_SOURCE_tx
abupy.env.g_data_cache_type = EDataCacheType.E_DATA_CACHE_CSV
abu.run_kl_update(start='2011-08-08', end='2017-08-08', market=EMarketTargetType.E_MARKET_TARGET_US, n_jobs=10)
import ipywidgets
# 避免使用notebook运行run all时运行不想执行的代码
_ = ipywidgets.interact_manual(tx_us)
In [11]:
%%time
from abupy import find_similar_with_cnt, ECoreCorrType
net_cg_ret = find_similar_with_cnt('usTSLA', cmp_cnt=252, show_cnt=10, rolling=True, \
show=True, corr_type=ECoreCorrType.E_CORE_TYPE_PEARS)
find_similar_with_se可视化与tsla相关top10,以及tsla相关性dict:从'2012-01-01'直到'2017-01-01'5年数据,非加权相关,皮尔逊
In [12]:
%%time
from abupy import find_similar_with_se, ECoreCorrType
net_cg_ret = find_similar_with_se('usTSLA', start='2012-01-01', end='2017-01-01', show_cnt=10, rolling=False, \
show=True, corr_type=ECoreCorrType.E_CORE_TYPE_PEARS)
find_similar_with_folds可视化与tsla相关top10,以及tsla相关性dict:n_folds=3(3年数据),非加权相关,E_CORE_TYPE_SPERM斯皮尔曼
In [13]:
%%time
from abupy import find_similar_with_folds, ECoreCorrType
net_cg_ret = find_similar_with_folds('usTSLA', n_folds=3, show_cnt=10, rolling=False, \
show=True, corr_type=ECoreCorrType.E_CORE_TYPE_SPERM)
In [12]:
from abupy import tl
# 以整个市场作为观察者,usTSLA与usNOAH的相关性
rank_score, sum_rank = tl.similar.calc_similar('usNOAH', 'usTSLA')
In [14]:
# 以usTSLA作为观察者,它与usNOAH的相关性数值
for ncr in net_cg_ret:
if ncr[0] == 'usNOAH':
print(ncr[1])
break
rank_score
Out[14]:
In [7]:
from abupy import tl
tl.similar.calc_similar_top('usTSLA')
Out[7]:
In [14]:
from abupy import tl
tl.similar.coint_similar('usTSLA')
Out[14]:
In [3]:
from abupy import AbuPickSimilarNTop
from abupy import AbuPickStockWorker
from abupy import AbuBenchmark, AbuCapital, AbuKLManager
from abupy import EMarketDataFetchMode
# 强制使用本地缓存数据
abupy.env.g_data_fetch_mode = EMarketDataFetchMode.E_DATA_FETCH_FORCE_LOCAL
In [4]:
benchmark = AbuBenchmark()
# 选股因子AbuPickSimilarNTop, 寻找与usTSLA相关性不低于0.95的股票
# 这里内部使用以整个市场作为观察者方式计算,即取值范围0-1
stock_pickers = [{'class': AbuPickSimilarNTop,
'similar_stock':'usTSLA', 'threshold_similar_min':0.95}]
# 从这几个股票里进行选股,只是为了演示方便,一般的选股都会是数量比较多的情况比如全市场股票
choice_symbols = ['usNOAH', 'usSFUN', 'usBIDU', 'usAAPL', 'usGOOG', 'usTSLA', 'usWUBA', 'usVIPS']
capital = AbuCapital(1000000, benchmark)
kl_pd_manager = AbuKLManager(benchmark, capital)
stock_pick = AbuPickStockWorker(capital, benchmark, kl_pd_manager, choice_symbols=choice_symbols, stock_pickers=stock_pickers)
stock_pick.fit()
stock_pick.choice_symbols
Out[4]:
通过选股因子first_choice属性执行批量优先选股操作,具体阅读源代码
In [17]:
benchmark = AbuBenchmark()
capital = AbuCapital(1000000, benchmark)
kl_pd_manager = AbuKLManager(benchmark, capital)
# 选股因子AbuPickSimilarNTop, 寻找与usTSLA相关性不低于0.95的股票
# 通过设置'first_choice':True,进行优先批量操作,默认从对应市场选股
stock_pickers = [{'class': AbuPickSimilarNTop, 'first_choice':True,
'similar_stock':'usTSLA', 'threshold_similar_min':0.95}]
choice_symbols = None
capital = AbuCapital(1000000, benchmark)
kl_pd_manager = AbuKLManager(benchmark, capital)
stock_pick = AbuPickStockWorker(capital, benchmark, kl_pd_manager, choice_symbols=choice_symbols, stock_pickers=stock_pickers)
stock_pick.fit()
stock_pick.choice_symbols
Out[17]:
In [ ]: