# 5.5 钟摆理论 · 钟摆理论的简单实现——完美躲过股灾和精准抄底

（1）根据格雷厄姆的成长价值公式进行估值，并且根据A股的实际情况或者市场情绪给予一定溢价或者折价。价值=当期(正常)利润×(8.5 + 两倍的预期年增长率)，其中的当期利润使用每股收益EPS进行衡量，预期年增长率使用EGRO/5表示，其中EGRO的计算方法为5年收益关于时间（年）进行线性回归的回归系数/5年收益均值的绝对值

（2）判断趋势有两种途径结合，一种是趋势已经向上，比较简单判断方法是五日线在十日线之上（这种判断方法犯错的几率较大，读者可以自行改进），另外一种是趋势由下向上逆转，即出现明显的底部形态。关于后者，我给出的判断标准为：股价相对于近期高点大幅下跌超过downPercent（例如30%），并且收盘价在五日线十日线之下，并且收红或者收星，跌幅小于7%

``````def preceding_date(date):
cal = cal[cal['isOpen']==1]
date = cal['calendarDate'].values[-2].replace('-','')
return date

def duotou_5_10(date, stockList, precedingDate=True):
if precedingDate:
date = preceding_date(date)
duotou = {}
if stockList is None or len(stockList) == 0:
return duotou
kLine = kLine.dropna()
for stock, ma5, ma10 in zip(kLine['secID'].values, kLine['MA5'].values, kLine['MA10'].values):
if ma5 > ma10:
duotou[stock] = True
else:
duotou[stock] = False
return duotou

stock_list = account.universe
current_date = account.current_date
date = current_date.strftime('%Y%m%d')
if precedingDate:
date = preceding_date(date)
eq_EPS_EGRO['Value'] = eq_EPS_EGRO['EPS']*(8.5+2*eq_EPS_EGRO['EGRO']/5)
eq_EPS_EGRO = eq_EPS_EGRO.dropna()
for stock, intrinsic_value in zip(eq_EPS_EGRO['secID'].values, eq_EPS_EGRO['Value'].values):
intrinsic_value = intrinsic_value*(1+overflow)
reference_price = account.referencePrice[stock]
if reference_price > 0 and reference_price < intrinsic_value:
return sorted(spread_rate, key=lambda k: k[-1], reverse=True)

'''

'''
def isButtom(date, stockList, precedingDate=True, downPercent=0.3):
if precedingDate:
rs = {}
if stockList is None or len(stockList) == 0:
return rs
dayInfo.dropna()
for stock in stockList:
stockDayInfo = dayInfo[dayInfo['secID']==stock]
closePrices = stockDayInfo['closePrice'].values
ma5 = np.mean(closePrices[-5:])
ma10 = np.mean(closePrices[-10:])
closePrice = closePrices[-1]
maxClosePrice = np.max(closePrices)
openPrice = stockDayInfo['openPrice'].values[-1]
preClosePrice = stockDayInfo['preClosePrice'].values[-1]
if (maxClosePrice-closePrice)/maxClosePrice > downPercent and closePrice < ma5 and ma5 < ma10 and (closePrice > openPrice or abs(closePrice-openPrice)/openPrice < 0.02) and abs(closePrice-preClosePrice)/preClosePrice<0.07:
rs[stock] = True
else:
rs[stock] = False
return rs
``````
``````import numpy as np

start = '2013-01-01'                       # 回测起始时间
end = '2015-10-01'                         # 回测结束时间
benchmark = 'HS300'                       # 策略参考标准
commission = Commission(buycost=0.0008, sellcost=0.0018)  # 佣金万八
universe = set_universe('CYB',date=end)           # Very Important Here!! 选股很重要！不要玩大烂臭！估值再低也别玩！
capital_base = 1000000                      # 起始资金
freq = 'd'                                 # 策略类型，'d'表示日间策略使用日线回测，'m'表示日内策略使用分钟线回测
refresh_rate = 1                           # 调仓频率，表示执行handle_data的时间间隔，若freq = 'd'时间间隔的单位为交易日，若freq = 'm'时间间隔为分钟

max_percent_of_a_stock = 1.0 # 单支股的最大仓位

def initialize(account):                   # 初始化虚拟账户状态
pass

def handle_data(account):                  # 每个交易日的买入卖出指令
global max_percent_of_a_stock
selist = []
current_date = account.current_date
current_date = current_date.strftime('%Y%m%d')

overflow = 0.15 # 根据情况给予一定的溢价（例如0.1)或者折价(例如-0.1)，也可以根据市场风险程度进行动态调节（此处读者可以自行发挥）

referencePortfolioValue = account.referencePortfolioValue

# 获取用来计算多头形态的股票列表
stock_set_for_duotou = []
stock_set_for_duotou.extend(account.avail_secpos.keys())
stock_set_for_duotou = list(set(stock_set_for_duotou))

duotou_5_10_Map = duotou_5_10(current_date, stock_set_for_duotou, precedingDate=True)
isButtom_Map = isButtom(current_date, stock_set_for_duotou, precedingDate=True, downPercent=0.3)

for stock in account.avail_secpos.keys():
if stock not in spread_rate and not duotou_5_10_Map.get(stock, False):
selist.append(stock)

for stock in selist:
sell_value = account.referencePrice[stock]*account.valid_secpos[stock]
order_to(stock, 0)

if stock not in account.valid_secpos: