Beispiel #1
0
 def __init__(self, strategy=None, best_ip={}):
     """
     构造函数
     :param strategy: 上层策略,主要用与使用write_log()
     """
     self.api = None
     self.connection_status = False  # 连接状态
     self.best_ip = best_ip
     self.symbol_exchange_dict = {}  # tdx合约与vn交易所的字典
     self.symbol_market_dict = copy.copy(
         INIT_TDX_MARKET_MAP)  # tdx合约与tdx市场的字典
     self.strategy = strategy
     self.future_contracts = get_future_contracts()
Beispiel #2
0
from vnpy_pro.app.cta_strategy.backtesting import BacktestingEnginePro
from vnpy_pro.app.cta_strategy.csv_backtesting import CsvBacktestingEngine
from vnpy.app.cta_strategy.base import BacktestingMode
from vnpy_pro.config import load_futures
from vnpy_pro.data.tdx.tdx_common import get_future_contracts

from worktable.strategies_storage.num4_renko.twine_strategy import TwineStrategy
from worktable.strategies_storage.num4_renko.renko import RenkoStrategy
from worktable.strategies_storage.num3_tools.tradedays import TradeDaysStrategy
# from worktable.strategies_storage.num4_renko.twine_strategy_v1 import TwineStrategy

test_future = "SR"

FUTURES = load_futures()
future_contracts = get_future_contracts()
# vt_symbol = test_future.upper() + "99." + future_contracts[test_future]["exchange"]
# print(vt_symbol)
# symbol_size = future_contracts[test_future]["symbol_size"]
# price_tick = future_contracts[test_future]["price_tick"]

vt_symbol = "btcusd.HUOBI"
symbol_size = 0.001
price_tick = 0.01

engine = BacktestingEnginePro()
engine.set_parameters(
    vt_symbol=vt_symbol,
    interval=Interval.MINUTE,
    start=datetime(2020, 4, 1),
    end=datetime(2020, 12, 1),
Beispiel #3
0
    def calculate_and_chart_daily_results(self, capital=10_000):
        """update daily_results,并绘制资金曲线图"""
        if self.instance_name is None:
            return
        if not os.path.exists(self.save_path):
            self.write_log(
                f"实例{self.instance_name} 不存在交易数据,无法update daily_results,并绘制资金曲线图"
            )
            return
        daily_results_file = os.path.join(self.save_path, "daily_results.csv")
        close_dict = load_json(os.path.join(self.save_path,
                                            "daily_close.json"))
        trades_file = os.path.join(self.save_path, "trades.csv")
        if not os.path.exists(trades_file):
            return
        trades_df = pd.read_csv(trades_file)
        trades_dict = trades_df.to_dict(orient="records")

        daily_results = {}
        for daily_date, daily_close in close_dict.items():
            daily_results[daily_date] = DailyResultPro(daily_date, daily_close)
        for trade in trades_dict:
            d = trade["datetime"][:10]
            # 防止对应的不存在收盘价,不存收盘以交易价为准
            daily_result = daily_results.get(d,
                                             DailyResultPro(d, trade["price"]))
            daily_result.add_trade(trade)

        daily_results_values = daily_results.values()
        if len(daily_results_values) != 0:
            future_contracts = get_future_contracts()
            symbol_letter = ''.join(
                re.split(r'[^A-Za-z]',
                         self.vt_symbol.split(".")[0]))
            symbol_info = future_contracts.get(symbol_letter, {})

            pre_close = 0
            start_pos = 0

            for daily_result in daily_results_values:
                # 手续费、滑点设置为0
                daily_result.calculate_pnl2(
                    pre_close, start_pos,
                    symbol_info.get("symbol_size", 1) *
                    symbol_info.get("margin_rate", 1), 0, 0, False)
                pre_close = daily_result.close_price
                start_pos = daily_result.end_pos

            results = defaultdict(list)
            for daily_result in daily_results_values:
                for key, value in daily_result.__dict__.items():
                    results[key].append(value)

            daily_df = DataFrame.from_dict(results).set_index("date")
            statistics = self.calculate_statistics_and_save(
                daily_df, self.save_path, capital)
            daily_df.to_csv(daily_results_file, encoding="utf_8_sig")
            draw_daily_results_chart(daily_df=daily_df,
                                     save_path=self.save_path)
            # self.write_log(f"实例{self.instance_name} update daily_results,并绘制资金曲线图成功")
            return statistics