"""
Name : 4375OS_07_26_trend.py
Book : Python for Finance
Publisher: Packt Publishing Ltd.
Author : Yuxing Yan
Date : 12/26/2013
email : yany@canisius.edu
paulyxy@hotmail.com
"""
import datetime
import numpy as np
import matplotlib.colors as colors
import matplotlib.finance as finance
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
startdate = datetime.date(2009,1,1)
today = enddate = datetime.date.today()
ticker = 'IBM'
fh = finance.fetch_historical_yahoo(ticker, startdate, enddate)
r = mlab.csv2rec(fh); fh.close()
r.sort()
def moving_average(x, n, type='simple'):
"""
compute an n period moving average.
type is 'simple' | 'exponential'
"""
x = np.asarray(x)
if type=='simple':
weights = np.ones(n)
else:
weights = np.exp(np.linspace(-1., 0., n))
weights /= weights.sum()
a = np.convolve(x, weights, mode='full')[:len(x)]
a[:n] = a[n]
return a
def relative_strength(prices, n=14):
"""
compute the n period relative strength indicator
http://stockcharts.com/school/doku.php?id=chart_school:glossary_r#relativestrengthindex
http://www.investopedia.com/terms/r/rsi.asp
"""
deltas = np.diff(prices)
seed = deltas[:n+1]
up = seed[seed>=0].sum()/n
down = -seed[seed<0].sum()/n
rs = up/down
rsi = np.zeros_like(prices)
rsi[:n] = 100. - 100./(1.+rs)
for i in range(n, len(prices)):
delta = deltas[i-1] # cause the diff is 1 shorter
if delta>0:
upval = delta
downval = 0.
else:
upval = 0.
downval = -delta
up = (up*(n-1) + upval)/n
down = (down*(n-1) + downval)/n
rs = up/down
rsi[i] = 100. - 100./(1.+rs)
return rsi
def moving_average_convergence(x, nslow=26, nfast=12):
"""
compute the MACD (Moving Average Convergence/Divergence) using a fast and slow exponential moving avg'
return value is emaslow, emafast, macd which are len(x) arrays
"""
emaslow = moving_average(x, nslow, type='exponential')
emafast = moving_average(x, nfast, type='exponential')
return emaslow, emafast, emafast - emaslow
plt.rc('axes', grid=True)
plt.rc('grid', color='0.75', linestyle='-', linewidth=0.5)
textsize = 9
left, width = 0.1, 0.8
rect1 = [left, 0.7, width, 0.2]
rect2 = [left, 0.3, width, 0.4]
rect3 = [left, 0.1, width, 0.2]
fig = plt.figure(facecolor='white')
axescolor = '#f6f6f6' # the axes background color
ax1 = fig.add_axes(rect1, axisbg=axescolor) #left, bottom, width, height
ax2 = fig.add_axes(rect2, axisbg=axescolor, sharex=ax1)
ax2t = ax2.twinx()
ax3 = fig.add_axes(rect3, axisbg=axescolor, sharex=ax1)
### plot the relative strength indicator
prices = r.adj_close
rsi = relative_strength(prices)
fillcolor = 'darkgoldenrod'
ax1.plot(r.date, rsi, color=fillcolor)
ax1.axhline(70, color=fillcolor)
ax1.axhline(30, color=fillcolor)
ax1.fill_between(r.date, rsi, 70, where=(rsi>=70), facecolor=fillcolor, edgecolor=fillcolor)
ax1.fill_between(r.date, rsi, 30, where=(rsi<=30), facecolor=fillcolor, edgecolor=fillcolor)
ax1.text(0.6, 0.9, '>70 = overbought', va='top', transform=ax1.transAxes, fontsize=textsize)
ax1.text(0.6, 0.1, '<30 = oversold', transform=ax1.transAxes, fontsize=textsize)
ax1.set_ylim(0, 100)
ax1.set_yticks([30,70])
ax1.text(0.025, 0.95, 'RSI (14)', va='top', transform=ax1.transAxes, fontsize=textsize)
ax1.set_title('%s daily'%ticker)
### plot the price and volume data
dx = r.adj_close - r.close
low = r.low + dx
high = r.high + dx
deltas = np.zeros_like(prices)
deltas[1:] = np.diff(prices)
up = deltas>0
ax2.vlines(r.date[up], low[up], high[up], color='black', label='_nolegend_')
ax2.vlines(r.date[~up], low[~up], high[~up], color='black', label='_nolegend_')
ma20 = moving_average(prices, 20, type='simple')
ma200 = moving_average(prices, 200, type='simple')
linema20, = ax2.plot(r.date, ma20, color='blue', lw=2, label='MA (20)')
linema200, = ax2.plot(r.date, ma200, color='red', lw=2, label='MA (200)')
last = r[-1]
s = '%s O:%1.2f H:%1.2f L:%1.2f C:%1.2f, V:%1.1fM Chg:%+1.2f' % (
today.strftime('%d-%b-%Y'),
last.open, last.high,
last.low, last.close,
last.volume*1e-6,
last.close-last.open )
t4 = ax2.text(0.3, 0.9, s, transform=ax2.transAxes, fontsize=textsize)
props = font_manager.FontProperties(size=10)
leg = ax2.legend(loc='center left', shadow=True, fancybox=True, prop=props)
leg.get_frame().set_alpha(0.5)
volume = (r.close*r.volume)/1e6 # dollar volume in millions
vmax = volume.max()
poly = ax2t.fill_between(r.date, volume, 0, label='Volume', facecolor=fillcolor, edgecolor=fillcolor)
ax2t.set_ylim(0, 5*vmax)
ax2t.set_yticks([])
### compute the MACD indicator
fillcolor = 'darkslategrey'
nslow = 26
nfast = 12
nema = 9
emaslow, emafast, macd = moving_average_convergence(prices, nslow=nslow, nfast=nfast)
ema9 = moving_average(macd, nema, type='exponential')
ax3.plot(r.date, macd, color='black', lw=2)
ax3.plot(r.date, ema9, color='blue', lw=1)
ax3.fill_between(r.date, macd-ema9, 0, alpha=0.5, facecolor=fillcolor, edgecolor=fillcolor)
ax3.text(0.025, 0.95, 'MACD (%d, %d, %d)'%(nfast, nslow, nema), va='top',
transform=ax3.transAxes, fontsize=textsize)
for ax in ax1, ax2, ax2t, ax3:
if ax!=ax3:
for label in ax.get_xticklabels():
label.set_visible(False)
else:
for label in ax.get_xticklabels():
label.set_rotation(30)
label.set_horizontalalignment('right')
ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
class MyLocator(mticker.MaxNLocator):
def __init__(self, *args, **kwargs):
mticker.MaxNLocator.__init__(self, *args, **kwargs)
def __call__(self, *args, **kwargs):
return mticker.MaxNLocator.__call__(self, *args, **kwargs)
ax2.yaxis.set_major_locator(MyLocator(5, prune='both'))
ax3.yaxis.set_major_locator(MyLocator(5, prune='both'))
plt.show()
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
python金融大数据分析源代码 (302个子文件)
26_trend.py 6KB
34_sobol_test.py 6KB
18_breuch_pagan_test_heterroskedasticity.py 4KB
38_simulation_efficient_frontier_different_corrcoef.py 3KB
67_efficient_portfolio3stocks.py 3KB
13_test_Heston_model.py 3KB
39_simulation_efficient_frontier_n_stocks.py 3KB
37_simulation_efficient_frontier2stocks.py 3KB
68_efficient_frontier.py 3KB
17_GJR_GARH_Sheppard.py 3KB
p4f.py 3KB
p4f.py 3KB
08_volatility_skewness.py 3KB
69_sharpe_ratio_optimal_portfolio.py 2KB
16_simulate_GARCH__from_R.py 2KB
40_implied_vol_American_call_Yahoo.py 2KB
32_barrier_up_out_in_call_parity_graph.py 2KB
26_binomial_two_step_graph_2.py 2KB
12_binomial_two_step_graph.py 2KB
39_implied_vol_American_call.py 2KB
12_Heston_statistic_volatility.py 2KB
16_IBM_candle_stick.py 2KB
21_risk_return_graph2.py 2KB
24_simulation_distribution.py 2KB
03_shapiro_normality_test.py 2KB
31_barrier_up_call.py 2KB
04_bs_call_with_comments.py 1KB
17_calendar_spread_call.py 1KB
41_put_call_ratio_short_period_add_trend.py 1KB
37_estimate_vol_using_option_data2.py 1KB
22_risk_return_graph3.py 1KB
04_test_constant_volatility_Ford.py 1KB
13_numvwe_stock_vs_portfolio_volatility.py 1KB
32_option_data_CBOE.py 1KB
19_breuch_pagan_test.py 1KB
17_last_30days.py 1KB
40_Pastor_Stambaugh.py 1KB
36_estimte_vol_using_optioin_data.py 1KB
19_long_term_forecast.py 1KB
17_implied_vol_put_min_value.py 1KB
10_color_bar.py 1KB
05_Dupont.py 1KB
60_moving_beta_annual.py 1KB
22_barrier_down_and_in_put.py 1KB
20_barrier_up_and_out_call.py 1KB
20_mutiple_IRR_f.py 1KB
20_bar_color_EPS.py 1KB
25_binomial_two_step_graph.py 1KB
14_terminal_stock_price.py 1KB
19_put_call_parity.py 1KB
13_multiple_IRRs.py 1KB
19_risk_return_graph.py 1KB
10_skewness_kurtosis_SP500.py 1KB
12_simulate_stock_price.py 1KB
18_fin101_help2.py 1KB
13_simulate_stock_price2dimentional.py 1KB
25_lookback_strike_is_minimum_price.py 1KB
34_math_formulae.py 1KB
58_Fama_MacBeth_regression.py 1KB
19_implied_vol_put_min_value.py 1KB
15_covered_call.py 1KB
31_price_movement.py 1KB
18_butterfly.py 1KB
07_save_call_put_pickle_format.py 1009B
28_Bootstrapping_function.py 1007B
29_ff_3_factor_model.py 1002B
30_two_stock_correlation_plot.py 997B
28_stock_vs_market_ret.py 990B
33_intraday_price_pattern.py 987B
18_annual_ret_comparison.py 977B
50_January_effect.py 974B
16_straddle.py 969B
16_implied_vol_function_call.py 969B
11_array_zero_one_identity.py 958B
20_binomial_one_step_graph.py 957B
12_pv_annuity_k_period_from_today.py 950B
15_simulation_call.py 924B
12_portfolio_diversification.py 923B
29_generate_bible_unique_words.py 920B
03_cumulative_standard_normal_CND.py 919B
38_put_call_ratio.py 916B
35_show.py 914B
09_lonormal_3_graphs.py 912B
26_CRR_American_put.py 908B
49_high_freq_my11_best.py 907B
16_Asian_call_average_price.py 906B
04_profit_loss_put.py 894B
05_bs_call.py 894B
21_debug.py 893B
05_LPSD_low_partial_deviation.py 878B
14_for_loop_implied_vol.py 878B
02_generate_ff_daily_pickle.py 873B
15_simulate_GARCH_process.py 869B
10_bs_put_scipy.py 863B
11_bs_call_with_dividend.py 849B
51_VaR.py 847B
09_bs_call_scipy.py 841B
31_merge_two_datasets_by_date.py 840B
29_binomial_tree_call_option_American.py 838B
11_select_m_stocks_from_n_stocks.py 831B
共 302 条
- 1
- 2
- 3
- 4
资源评论
fjchenq
- 粉丝: 14
- 资源: 66
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功