示例#1
0
def show_macd():
    """
    MACD交易策略
    :return:
    """
    CBClose = get_CBClose()
    DIF = ma.ewma_cal(CBClose, 12, 2 / (1 + 12)) - ma.ewma_cal(CBClose, 26, 2 / (1 + 26))
    print(DIF.tail(n=3))
    DEA = ma.ewma_cal(DIF, 9, 2 / (1 + 9))
    print(DEA.tail())
    MACD = DIF - DEA
    print("MACD tail")
    print(MACD.tail(n=3))
    # plt.subplot(211)
    # plt.plot(DIF['2015'], label='DIF', color='k')
    # plt.plot(DEA['2015'], label='DEA', color='b', linestyle='dashed')
    # plt.title("信号线DIF与DEA")
    # plt.legend()
    # plt.subplot(212)
    # plt.bar(left=MACD['2015'].index, height=MACD['2015'], label='MACD', color='r')
    # plt.legend()
    macddata = pd.DataFrame()
    macddata['DIF'] = DIF['2015']
    macddata['DEA'] = DEA['2015']
    macddata['MACD'] = MACD['2015']
    import candle
    ChinaBank = pd.read_csv(r"./data/ChinaBank.csv")
    candle.candleLinePlots(
        ChinaBank['2015'],
        candleTitle='中国银行2015年日K线图',
        splitFigures=True,
        Data=macddata,
        ylabel='MACD'
    )
示例#2
0
         color='b',
         linestyle='dashed')
plt.title("2013年中国联通股价唐奇安通道")
plt.ylim(2.9, 3.9)
plt.legend()



upDownDC=pd.DataFrame({'upboundDC':upboundDC,\
                      'downboundDC':downboundDC})
ChinaUnicom13 = ChinaUnicom['2013-01-01':'2013-06-28']
upDownDC13 = upDownDC['2013-01-01':'2013-06-28']

import candle
candle.candleLinePlots(candleData=ChinaUnicom13,\
        candleTitle='中国联通2013年上半年K线图及唐奇安通道',\
        Data=upDownDC13)


def upbreak(tsLine, tsRefLine):
    n = min(len(tsLine), len(tsRefLine))
    tsLine = tsLine[-n:]
    tsRefLine = tsRefLine[-n:]
    signal = pd.Series(0, index=tsLine.index)
    for i in range(1, len(tsLine)):
        if all([tsLine[i] > tsRefLine[i], tsLine[i - 1] < tsRefLine[i - 1]]):
            signal[i] = 1
    return (signal)


def downbreak(tsLine, tsRefLine):
示例#3
0
                     colorup='r',colordown='g')
    ax.set_title(candleTitle)
    plt.setp(ax.get_xticklabels(),\
             rotation=20,\
             horizontalalignment='center')
    ax.autoscale_view()

    return (plt.show())


#Candle 模组是本书自己编的模组,里面有绘制K线函数Candleplot
import candle

Vanke15 = Vanke['2015']
candle.candleLinePlots(Vanke['2015'],\
               candleTitle='万科股票2015年日K线图',\
               splitFigures=True,Data=momen35['2015'],\
               title='35日动量',ylabel='35日动量')

# 使用上面定义的函数
candleLinePlots(Vanke['2015'],\
               candleTitle='万科股票2015年日K线图',\
               splitFigures=True,Data=momen35['2015'],\
               title='35日动量',ylabel='35日动量')

Close = Vanke.Close
momen35 = momentum(Close, 35)
momen35.head()
signal = []
for i in momen35:
    if i > 0:
        signal.append(1)
示例#4
0
plt.legend()
plt.subplot(212)
plt.bar(left=MACD['2016-12'].index,\
        height=MACD['2016-12'],\
        label='MACD',color='r')
plt.title('柱狀圖MACD')
plt.legend()

macddata = pd.DataFrame()
macddata['DIF'] = DIF['2016-08':'2016-12']
macddata['DEA'] = DEA['2016-08':'2016-12']
macddata['MACD'] = MACD['2016-08':'2016-12']

import candle
candle.candleLinePlots(TSMC['2016-08':'2016-12'],\
              candleTitle='台積電2016年8月到12月份的日K線圖',\
              splitFigures=True,Data=macddata,\
              ylabel='MACD')

DEA = DEA.dropna()
DIF = DIF[DEA.index]
macdSignal = pd.Series(0, index=DIF.index)
for i in range(1, len(DIF)):
    if all([DIF[i] > DEA[i] > 0.0, DIF[i - 1] < DEA[i - 1]]):
        macdSignal[i] = 1
    elif all([DIF[i] < DEA[i] < 0.0, DIF[i - 1] > DEA[i - 1]]):
        macdSignal[i] = -1
macdSignal.tail()

macdTrade = macdSignal.shift(1)
macdRet = (tsmcRet * macdTrade).dropna()
macdRet[macdRet == -0] = 0
示例#5
0
ret = (zgyh.Close - zgyh.Close.shift(1)) / zgyh.Close.shift(1)
signal = np.all([data.Close > data.SMA, data.Mom > 0], 0)
signal = pd.Series(signal, index=ret[14:].index)
ret = ret[15:] * signal.shift(1)[1:]
ret.sum()

#3.
aapl = pd.read_csv('Data/Part5/004/problem30-3.csv', index_col='date')

aapl.index.name = 'Date'

aapl.index = pd.to_datetime(aapl.index, format='%Y-%m-%d')

import candle
candle.candleLinePlots(aapl['2014-01':'2014-02'],
                       candleTitle='Candle Plot of AAPL',
                       Data=aapl.Close['2014-01':'2014-02'])

aapl1 = aapl[:'2014-05']
#因为苹果发放了股利,为了价格的一致性,我们选取了Adjusted Price,即复权过的价格
dif = ma.ewmaCal(aapl1.Adjusted, 12, 2 / 13) - ma.ewmaCal(
    aapl1.Adjusted, 26, 2 / 27)
dif = dif[25:]
dea = ma.ewmaCal(dif, 9, 2 / 10)
dea = dea[8:]
dif = dif[8:]

macd = dif - dea

plt.subplot(211)
plt.plot(dif[12:], label="DIF", color='k')
plt.title("信号线DIF与DEA")
plt.legend()
plt.subplot(212)
plt.bar(left=MACD['2015'].index,\
        height=MACD['2015'],\
        label='MACD',color='r')
plt.legend()

macddata = pd.DataFrame()
macddata['DIF'] = DIF['2015']
macddata['DEA'] = DEA['2015']
macddata['MACD'] = MACD['2015']

import candle
candle.candleLinePlots(ChinaBank['2015'],\
              candleTitle='中国银行2015年日K线图',\
              splitFigures=True,Data=macddata,\
              ylabel='MACD')

macdSignal = pd.Series(0, index=DIF.index)
for i in range(1, len(DIF)):
    if all([DIF[i] > DEA[i] > 0.0, DIF[i - 1] < DEA[i - 1]]):
        macdSignal[i] = 1
    elif all([DIF[i] < DEA[i] < 0.0, DIF[i - 1] > DEA[i - 1]]):
        macdSignal[i] = -1
macdSignal.tail()

macdTrade = macdSignal.shift(1)

CBRet = CBClose / CBClose.shift(1) - 1
macdRet = (CBRet * macdTrade).dropna()
macdRet[macdRet == -0] = 0
示例#7
0
stock_data2 = stock_data.iloc[:, [4, 5, 6, 7, 2]]  # Open High Low Close Volume


#momentum function
def momentum(price, periond):
    lagPrice = price.shift(periond)
    momen = price - lagPrice
    momen = momen.dropna()
    return (momen)


Close = stock_data.Close

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, WeekdayLocator, \
                                DayLocator, MONDAY, date2num
from mpl_finance import candlestick_ohlc

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

momen35 = momentum(Close, 7)
import candle
candle.candleLinePlots(stock_data2,\
               candleTitle=u'TW Stock:2330 K Line',\
               splitFigures=True,Data=momen35,\
               title=u'7 day momentum',ylabel=u'7 day momentum')

plt.show()
示例#8
0
plt.plot(boundDC.midboundDC[:'2015-06-30'],
         label="midboundDC",
         color='r',
         linestyle='-.')
plt.plot(boundDC.downboundDC[:'2015-06-30'],
         label="downboundDC",
         color='b',
         linestyle='dashed')
plt.title("2015年上半年黑松股價唐奇安通道")
plt.legend()

import candle

candle.candleLinePlots(
    candleData=HeySong[:'2015-06-30'],
    candleTitle='2015年上半年黑松股票的K線圖及唐奇安通道',
    splitFigures=False,
    Data=boundDC[:'2015-06-30'][['upboundDC', 'downboundDC']])


def upbreak(tsLine, tsRefLine):
    n = min(len(tsLine), len(tsRefLine))
    tsLine = tsLine[-n:]
    tsRefLine = tsRefLine[-n:]
    signal = pd.Series(0, index=tsLine.index)
    for i in range(1, len(tsLine)):
        if all([tsLine[i] > tsRefLine[i], tsLine[i - 1] < tsRefLine[i - 1]]):
            signal[i] = 1
    return (signal)

示例#9
0
    candlestick_ohlc(ax,listData, width=0.7,\
                     colorup='r',colordown='g')
    ax.set_title(candleTitle)
    plt.setp(ax.get_xticklabels(),\
             rotation=20,\
             horizontalalignment='center')
    ax.autoscale_view()
    return (plt.show())


#candle 模組是本書編的模組,裡面有繪製K線函數candleLinePlots
import candle
Foxconn15 = Foxconn['2015']
candle.candleLinePlots(Foxconn15,\
               candleTitle='鴻海股票2015年日K線圖',\
               splitFigures=True,Data=momen35['2015'],\
               title='35日動量',ylabel='35日動量')

Close = Foxconn.Close
momen35 = momentum(Close, 35)
momen35.head()

signal = [1 if momen35Value > 0 else -1 for momen35Value in momen35]
signal = pd.Series(signal, index=momen35.index)
signal.head()

tradeSig = signal.shift(1)
ret = Close / Close.shift(1) - 1
Mom35Ret = (ret * (signal.shift(1))).dropna()
Mom35Ret[:5]
示例#10
0
print(Vanke.head(10))
Close = Vanke.Close
# print(Close.describe())
lag5Close = Close.shift(5)
print(lag5Close.head(10))
monmentum5 = Close - lag5Close
print(monmentum5.tail())
Momen5 = Close / lag5Close - 1
Momen5.dropna(inplace=True)
print(Momen5[:5])
print(momentum(Close, 5).tail())

# plt.subplot(211)
# plt.plot(Close, "b*")
# plt.xlabel('date')
# plt.ylabel('Close')
# plt.title('万科股份5日动量图')
#
# plt.subplot(212)
# plt.plot(monmentum5, "r-*")
# plt.xlabel('date')
# plt.ylabel('Momentum5')
#
# plt.show()

momen35 = momentum(Close, 35)
candle.candleLinePlots(Vanke['2015'].copy(),
                       candleTitle='万科股票2015年日K线图',
                       Data=momen35['2015'],
                       ylabel='35日动量')
示例#11
0
                         'downBBand':downBBand[(period-1):],\
                         'sigma':sigma[(period-1):]})
    return (BBands)


#1.
GSPC = pd.read_csv('Data/Part5/005/problem31-1.csv', index_col='date')

GSPC.index.name = 'Date'

GSPC.index = pd.to_datetime(GSPC.index, format='%Y-%m-%d')

GSPC1 = GSPC[:'2014-02']

candle.candleLinePlots(GSPC1,
                       candleTitle='Candle Plot of SPY500',
                       Data=GSPC1.Close)

candle.candleLinePlots(GSPC1,
                       candleTitle='Candle Plot of SPY500',
                       Data=bbands(GSPC1.Close)[['downBBand', 'upBBand']])

upbound = pd.rolling_max(GSPC.High, 10)
lowbound = pd.rolling_min(GSPC.Low, 10)
midbound = (upbound + lowbound) / 2
bounds = pd.concat([upbound, lowbound, midbound], 1)
bounds.columns = ['upbound', 'lowbound', 'midbound']
bounds.dropna().plot()

std = pd.rolling_std(GSPC.Close, 10)
midbound = pd.rolling_mean(GSPC.Close, 10)