# 可以自己import我们平台支持的第三方python模块,比如pandas、numpy等。
import math
import numpy as np
import pandas as pd
import talib
OBSERVATION=40
# 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。
def init(context):
context.benchmark='000037.XSHG'
context.stocks =industry('C27')
update_universe(context.stocks)
get_parameter(context,None)
context.number=12
scheduler.run_weekly(get_parameter,weekday=1)
scheduler.run_daily(handle_bar2)
# 你选择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新
def get_parameter(context,bar_dict):
#获取基本面数据
fundamental_df = get_fundamentals(
query(fundamentals.eod_derivative_indicator.pe_ratio,fundamentals.eod_derivative_indicator.pb_ratio,fundamentals.eod_derivative_indicator.market_cap,fundamentals.financial_indicator.inc_revenue,fundamentals.financial_indicator.inc_profit_before_tax
).filter(
fundamentals.income_statement.stockcode.in_(context.stocks)
).filter(
fundamentals.eod_derivative_indicator.pb_ratio>0
).filter(
fundamentals.eod_derivative_indicator.pe_ratio>0
).filter(
fundamentals.financial_indicator.inc_revenue>-99
).filter(
fundamentals.financial_indicator.inc_profit_before_tax>-99
)
)
df=fundamental_df.T
#对基本面数据进行处理,便于计算
pe_log=list(map(lambda x:math.log(float(x)),df.iloc[:,0]))
pb_log=list(map(lambda x:(float(x)),df.iloc[:,1]))
aaa=list(map(lambda x:float(x),df.iloc[:,2]))
aaa=pd.DataFrame(aaa)
meanc=float(df.iloc[:,2].mean())
sdc=float(aaa.std())
cap_sd=list(map(lambda x:(float(x)-meanc)/sdc,df.iloc[:,2]))
inc_revenue=list(map(lambda x:math.log(float(x)*0.01+1),df.iloc[:,3]))
inc_profit=list(map(lambda x:math.log(float(x)*0.01+1),df.iloc[:,4]))
#通过多元回归得到相应的参数
x=[]
x.append(pb_log)
x.append(inc_revenue)
x.append(inc_profit)
x.append(cap_sd)
#x.append(pcf_log)
x=np.mat(x)
y=np.mat(pe_log)
xx=(x*x.T).I
beta=xx*(x*y.T)
mean=np.mat([sum(pb_log)/len(pb_log),sum(inc_revenue)/len(inc_revenue),sum(inc_profit)/len(inc_profit),sum(cap_sd)/len(cap_sd)])
alpha=sum(pe_log)/len(pe_log)-mean*beta
context.alpha=alpha
context.beta=beta
def handle_bar(context, bar_dict):
pass
def handle_bar2(context, bar_dict):
#获取基本面数据
fundamental_df = get_fundamentals(
query(fundamentals.eod_derivative_indicator.pe_ratio,fundamentals.eod_derivative_indicator.pb_ratio,fundamentals.eod_derivative_indicator.market_cap,fundamentals.financial_indicator.inc_revenue,fundamentals.financial_indicator.inc_profit_before_tax
).filter(
fundamentals.income_statement.stockcode.in_(context.stocks)
).filter(
fundamentals.eod_derivative_indicator.pb_ratio>0
).filter(
fundamentals.eod_derivative_indicator.pe_ratio>0
).filter(
fundamentals.financial_indicator.inc_revenue>-99
).filter(
fundamentals.financial_indicator.inc_profit_before_tax>-99
)
)
df=fundamental_df.T
#处理基本面数据
#logger.info(df)
df['pe_log']=list(map(lambda x:math.log(float(x)),df.iloc[:,0]))
pb_log=list(map(lambda x:(float(x)),df.iloc[:,1]))
aaa=list(map(lambda x:float(x),df.iloc[:,2]))
aaa=pd.DataFrame(aaa)
meanc=float(df.iloc[:,2].mean())
sdc=float(aaa.std())
cap_sd=list(map(lambda x:(float(x)-meanc)/sdc,df.iloc[:,2]))
inc_revenue=list(map(lambda x:math.log(float(x)*0.01+1),df.iloc[:,3]))
inc_profit=list(map(lambda x:math.log(float(x)*0.01+1),df.iloc[:,4]))
x=[]
x.append(pb_log)
x.append(inc_revenue)
x.append(inc_profit)
x.append(cap_sd)
#x.append(pcf_log)
x=np.mat(x)
#利用回归参数计算价值
pe_log_es=x.T*context.beta+context.alpha
df['pe_log_es']=pe_log_es
df['rate']=df['pe_log']/df['pe_log_es']
df=df[df['rate']>0]
df=df.sort(columns='rate')
df=df.head(context.number)
context.to_buy=df.T.columns.values
rebalance(context, bar_dict)
def rebalance(context, bar_dict):
stocks = set(context.to_buy)
holdings = set(get_holdings(context))
to_buy = stocks - holdings
to_sell = holdings - stocks
to_buy2= stocks - holdings
for stock in to_sell:
if bar_dict[stock].is_trading:
order_target_percent(stock , 0)
#logger.info(len(to_buy))
to_buy = get_trading_stocks(to_buy, context, bar_dict)
if len(to_buy) >0:
cash = context.portfolio.cash
average_value = 0.98 * cash / len(to_buy)
for stock in to_buy:
if bar_dict[stock].is_trading:
order_target_percent(stock , 0.142)
def get_trading_stocks(to_buy, context, bar_dict):
trading_stocks = []
for stock in to_buy:
if bar_dict[stock].is_trading:
trading_stocks.append(stock)
return trading_stocks
def get_holdings(context):
positions = context.portfolio.positions
holdings = []
for position in positions:
if positions[position].quantity > 0:
holdings.append(position)
return holdings