米匡框架实现量化交易炒股
生活随笔
收集整理的這篇文章主要介紹了
米匡框架实现量化交易炒股
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
# 可以自己import我們平臺(tái)支持的第三方python模塊,比如pandas、numpy等。
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression # 線性回歸算法正規(guī)方程求解# 在這個(gè)方法中編寫任何的初始化邏輯。context對(duì)象將會(huì)在你的算法策略的任何方法之間做傳遞。
def init(context):# 在context中保存全局變量# 股票池初始化# 滬深300--在滬市和深市中表現(xiàn)較好的300支股票context.hs300 = index_components("000300.XSHG")weight = np.array([0.02953221, -0.04920124, -0.10791485, 0.00801783, -0.03613599, 0.1310877, -0.03030564, 0.40286239,-0.30166898])context.weight = np.mat(weight).Tcontext.stock_num = 20scheduler.run_monthly(mylineRegression, tradingday=1) # 每月運(yùn)行一次,每月第一天運(yùn)行#調(diào)用下面的mylneRegression函數(shù),框架封裝好def three_sigma(data):"""進(jìn)行3sigma離群值處理:param data: 傳入的數(shù)據(jù)
# :return: 拉回離群值之后的data"""up = data.mean() + 3 * data.std()low = data.mean() - 3 * data.std()# 超過上限用上限代替np.where(data > up, up, data)np.where(data < low, low, data)return datadef stand_sca(data):"""#標(biāo)準(zhǔn)差標(biāo)準(zhǔn)化數(shù)據(jù):param data: c傳入的數(shù)據(jù):return: 標(biāo)準(zhǔn)化之后的數(shù)據(jù)"""# mean()#均值;std()#標(biāo)準(zhǔn)差data = (data - data.mean()) / data.std()return data#數(shù)組和DataFrame的主要區(qū)別是DataFrame有索引def deal_with_data(data):"""數(shù)據(jù)處理"""# 1、缺失值處理data.dropna(axis=0, how='any', inplace=True)# 2、去極值# data=three_sigma(data)# #3、標(biāo)準(zhǔn)化# data=stand_sca(data)for column in data.columns:# 2、去極值data.loc[:, column] = three_sigma(data.loc[:, column])market_cap = data.loc[:, 'market_cap']# #3、標(biāo)準(zhǔn)化data.loc[:, column] == stand_sca(data.loc[:, column])# 市值中性化# if column=市值因子# continueif column == 'market_cap':continuelr = LinearRegression()x = market_capy = data.loc[:, column]# 訓(xùn)練模型lr.fit(x.values.reshape(-1, 1), y)# 進(jìn)行預(yù)測(cè)y_predict = lr.predict(x.values.reshape(-1, 1))# 相減data.loc[:, column] = y - y_predictreturn datadef tiaocang(context, stock_list):"""進(jìn)行股票買賣"""# 查詢倉(cāng)位for tmp in context.portfolio.positions.keys():if tmp not in stock_list:# 賣出,全部賣出order_target_percent(tmp, 0)# 買入# 平均買for tmp in stock_list:order_target_percent(tmp, 1 / len(stock_list))def mylineRegression(context, bar_dict):"""每月需要處理的功能"""# 1、獲取財(cái)務(wù)數(shù)據(jù)# 構(gòu)建queryq = query(fundamentals.eod_derivative_indicator.pe_ratio, fundamentals.eod_derivative_indicator.pb_ratio,fundamentals.eod_derivative_indicator.market_cap, fundamentals.financial_indicator.ev,fundamentals.financial_indicator.return_on_asset_net_profit,fundamentals.financial_indicator.du_return_on_equity, fundamentals.financial_indicator.earnings_per_share,fundamentals.income_statement.revenue, fundamentals.income_statement.total_expense).filter(fundamentals.stockcode.in_(context.hs300))fund = get_fundamentals(q)# 獲取到財(cái)務(wù)數(shù)據(jù)# print(fund.T)context.factor_data = fund.T# 數(shù)據(jù)處理context.factor_data = deal_with_data(context.factor_data)# print(context.factor_data.shape)# 構(gòu)建因子與下期收益之間的線性回歸# factor_data * w =下期收益"""context.factor_data.loc[:, 'return'] = np.dot(context.factor_data, context.weight)# 要拿到收益較高的股票代碼--進(jìn)行買賣stock_list = context.factor_data.loc[:, 'return'].sort_values(ascending=False)[:context.stock_num].indexprint(stock_list)# 進(jìn)行買賣tiaocang(context, stock_list)# before_trading此函數(shù)會(huì)在每天策略交易開始前被調(diào)用,當(dāng)天只會(huì)被調(diào)用一次
def before_trading(context):# 可以獲取賬戶資金或者在每天交易之前做一些操作pass# print(context.hs300)# 你選擇的證券的數(shù)據(jù)更新將會(huì)觸發(fā)此段邏輯,例如日或分鐘歷史數(shù)據(jù)切片或者是實(shí)時(shí)數(shù)據(jù)切片更新
def handle_bar(context, bar_dict):# 開始編寫你的主要的算法邏輯pass# bar_dict[order_book_id] 可以拿到某個(gè)證券的bar信息# context.portfolio 可以拿到現(xiàn)在的投資組合信息# 使用order_shares(id_or_ins, amount)方法進(jìn)行落單#產(chǎn)生交易信號(hào)、進(jìn)行訂單創(chuàng)建# TODO: 開始編寫你的算法吧!# order_shares(context.s1, 1000)# print('handle_bar')# after_trading函數(shù)會(huì)在每天交易結(jié)束后被調(diào)用,當(dāng)天只會(huì)被調(diào)用一次
def after_trading(context):# 每日結(jié)束時(shí)做一些操作pass# print('after_trading')
結(jié)果:
總結(jié)
以上是生活随笔為你收集整理的米匡框架实现量化交易炒股的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据分析pandas属性实现统计分析
- 下一篇: pandas数据存储于读取