一、簡介
Easyquant是一個用Python編寫的股票量化交易框架,可以幫助開發(fā)者快速地實現(xiàn)量化策略。
Easyquant具有以下特點:
簡單易用,代碼量少,不需要太多編程基礎(chǔ)。 支持多賬戶,可以滿足不同交易者的需求。 支持實時模擬和回測模式,方便開發(fā)者檢驗策略。
# 安裝easyquant
pip install easyquant
# 導(dǎo)入easyquant
from easyquant import StrategyTemplate, DefaultLogHandler, settings
class MyStrategy(StrategyTemplate):
name = 'mystrategy'
def strategy(self, event):
# 編寫交易策略的代碼
pass
def log_handler(self):
# 自定義日志的輸出方式
return DefaultLogHandler(self.name, log_type=settings.LOGGER_HANDLER)
if __name__ == '__main__':
mystrategy = MyStrategy()
mystrategy.run()
二、數(shù)據(jù)獲取
獲取股票數(shù)據(jù)是開發(fā)量化交易策略的重要任務(wù)。Easyquant提供了多種數(shù)據(jù)源供開發(fā)者使用:
Tushare Sina財經(jīng) 聚寬量化 通聯(lián)數(shù)據(jù) 新浪股票數(shù)據(jù)接口下面以Tushare為例,演示如何獲取股票數(shù)據(jù):
# 安裝tushare
pip install tushare
# 導(dǎo)入tushare
import tushare as ts
# 獲取滬深股票列表
stock_list = ts.get_stock_basics()
# 獲取指定股票的歷史k線數(shù)據(jù)
k_data = ts.get_k_data('000001', start='2021-01-01')
三、交易策略
Easyquant提供了一個模板StrategyTemplate,開發(fā)者只需要繼承這個模板,實現(xiàn)其中的strategy方法即可編寫自己的交易策略。
下面是一個例子:
from easyquant import StrategyTemplate, DefaultLogHandler
class MyStrategy(StrategyTemplate):
name = 'mystrategy'
def strategy(self, event):
# 獲取當(dāng)前股票的k線數(shù)據(jù)
k_data = self.get_kline_data(event.stock_code)
# 判斷是否買入
if k_data['ma5'] > k_data['ma60']:
self.buy(stock_code=event.stock_code, price=event.last_price)
# 判斷是否賣出
if k_data['ma5'] < k_data['ma60']:
self.sell(stock_code=event.stock_code, price=event.last_price)
def log_handler(self):
return DefaultLogHandler(self.name)
if __name__ == '__main__':
mystrategy = MyStrategy()
mystrategy.run()
四、交易模擬
Easyquant提供了實時模擬和回測模式,方便開發(fā)者檢驗自己的交易策略。
下面是一個例子:
# 導(dǎo)入模擬器
from easyquant import SimulationTrader
# 導(dǎo)入策略
from my_strategy import MyStrategy
class MySimulationTrader(SimulationTrader):
def __init__(self):
super().__init__()
# 設(shè)置初始資金
self.set_cash(100000)
# 導(dǎo)入策略
self.strategy = MyStrategy()
if __name__ == '__main__':
# 運行模擬器
MySimulationTrader().run()
五、交易回測
Easyquant提供了多種回測方法,可以根據(jù)需求選擇不同的方法進行回測。
下面是一個例子:
# 導(dǎo)入回測器
from easyquant import BacktestTrader
# 導(dǎo)入策略
from my_strategy import MyStrategy
class MyBacktestTrader(BacktestTrader):
def __init__(self):
super().__init__()
# 設(shè)置回測起始和結(jié)束時間
self.set_backtest_period('2021-01-01', '2021-06-30')
# 導(dǎo)入策略
self.strategy = MyStrategy()
if __name__ == '__main__':
# 運行回測器
MyBacktestTrader().run()