跳轉到

finlab.backtest

finlab.backtest.sim

sim(position, resample=None, resample_offset=None, trade_at_price='close', position_limit=1, fee_ratio=1.425 / 1000, tax_ratio=3 / 1000, name='未命名', stop_loss=None, take_profit=None, trail_stop=None, touched_exit=False, retain_cost_when_rebalance=False, stop_trading_next_period=True, live_performance_start=None, mae_mfe_window=0, mae_mfe_window_step=1, market='AUTO', upload=True, fast_mode=False, notification_enable=False, line_access_token='')

Simulate the equity given the stock position history. 回測模擬股票部位所產生的淨值報酬率。

PARAMETER DESCRIPTION
position

買賣訊號紀錄。True 為持有, False 為空手。 若選擇做空position,只要將 sim(position) 改成負的 sim(-position.astype(float))即可做空。

TYPE: DataFrame or Series

resample

交易週期。將 position 的訊號以週期性的方式論動股票,預設為每天換股。其他常用數值為 W、 M 、 Q (每週、每月、每季換股一次),也可以使用 W-Fri 在週五的時候產生新的股票清單,並且於下週交易日下單。

  • D: Daily
  • W: Weekly
  • W-Wed: Every Wednesday
  • M: Monthly
  • MS: Start of every month
  • Q: Quarterly
  • QS: Start of every quarter

Note

'D'與'None'的差別? resample='D' 的意義為每天隨股價變化做再平衡,就算當天股票清單沒變,但股票漲跌後,部位大小會變化,而 resample='D' 會強制再平衡,平均分散風險。

但是當 resample=None 的話,假如清單不變,則不會強制再平衡,只有清單改變時,才做再平衡。適用情境在較常選到大波段標的的趨勢策略,較有機會將強勢股留下,而不會汰強留弱做再平衡。

另外 resample 也接受 pd.DataFrame 以及 pd.Series,並且將其 index 用來當成換股的時間點,例如以下的範例:

from finlab import backtest, data

rev = data.get('monthly_revenue:當月營收')
position = ...

# 月營收發布時才換股
backtest.sim(position, resample=rev)

TYPE: (str, None, DataFrame, Series, FinlabDataFrame) DEFAULT: None

resample_offset

交易週期的時間位移,例如。

  • '1D': 位移一天
  • '1H': 位移一小時

TYPE: str or None DEFAULT: None

trade_at_price

選擇回測之還原股價以收盤價或開盤價計算,預設為'close'。可選'close'、'open'、'open_close_avg'、'high_low_avg'或 'price_avg'。

TYPE: str or DataFrame DEFAULT: 'close'

position_limit

maximum amount of investing a stock. 單檔標的持股比例上限,控制倉位風險。預設為None。範例:0.2,代表單檔標的最多持有 20 % 部位。

TYPE: float DEFAULT: 1

fee_ratio

fee ratio of buying or selling a stock. 交易手續費率,預設為台灣無打折手續費 0.001425。可視個人使用的券商優惠調整費率。

TYPE: float DEFAULT: 1.425 / 1000

tax_ratio

tax ratio of selling a stock. 交易稅率,預設為台灣普通股一般交易交易稅率 0.003。若交易策略的標的皆為ETF,記得設成 0.001。

TYPE: float DEFAULT: 3 / 1000

name

name of the strategy. 策略名稱,預設為 未指名。策略名稱。相同名稱之策略上傳會覆寫。命名規則:全英文或開頭中文,不接受開頭英文接中文。

TYPE: str DEFAULT: '未命名'

stop_loss

停損基準,預設為None,不執行停損。範例:0.1,代表從再平衡開始,虧損 10% 時產生出場訊號。

TYPE: float DEFAULT: None

take_profit

停利基準,預設為None,不執行停利。範例:0.1,代表從再平衡開始, 10% 時產生出場訊號。

TYPE: float DEFAULT: None

trail_stop

移動停損停利基準,預設為None,不執行。範例:0.1,代表從最高點開始下跌,跌至 10% 時產生出場訊號。

TYPE: float DEFAULT: None

touched_exit

是否在回測時,使用觸價停損停利?預設為 False。

TYPE: bool DEFAULT: False

retain_cost_when_rebalance

預設回測時,會將進場股票進場成本更新到到新的 rebalance 的當天價格,假如希望保留原本的進場價格當成停損停利的依據,可以設定為 True

TYPE: bool DEFAULT: False

stop_trading_next_period

當期已經停損停利,則下一期不買入,預設為 True。

TYPE: bool DEFAULT: True

live_performance_start

策略建構的日期,例如 2022-01-01 此日期之前,策略未撰寫,此日期之後則視為與實單有類似效果,實際不影響回測的結果,單純紀錄而已。

TYPE: str DEFAULT: None

mae_mfe_window

計算mae_mfe於進場後於不同持有天數下的數據變化,主要應用為edge_ratio (優勢比率)計算。預設為0,則Report.display_mae_mfe_analysis(...)中的edge_ratio不會顯現。

TYPE: int DEFAULT: 0

mae_mfe_window_step

與mae_mfe_window參數做搭配,為時間間隔設定,預設為1。若mae_mfe_window設20,mae_mfe_window_step設定為2,相當於python的range(0,20,2),以2日為間距計算mae_mfe。

TYPE: int DEFAULT: 1

market

可選擇'TW_STOCK', 'CRYPTO',分別為台股或加密貨幣, 或繼承 finlab.market_info.MarketInfo 開發回測市場類別。

TYPE: str or MarketInfo DEFAULT: 'AUTO'

upload

上傳策略至finlab網站,預設為True,上傳策略。 範例: False,不上傳,可用 finlab.backtest.sim(position, upload=False, ...).display() 快速檢視策略績效。

TYPE: bool DEFAULT: True

fast_mode

預設為False,若設定為True,則會使用快速模式,快速模式會忽略所有的停利停損設定,並且只有換股日進行報酬率模擬,因此會有一些誤差,當持有較多檔股票時,可以大幅加速回測速度。

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Report

回測數據報告

Examples:

Assume the history of portfolio is construct as follows: When market close on 2021-12-31, the portfolio {B: 0.2, C: 0.4} is calculated. When market close on 2022-03-31, the portfolio {A:1} is calculated.

Stock 2330 Stock 1101 Stock 2454
2021-12-31 0% 20% 40%
2022-03-31 100% 0% 0%
2022-06-30 100% 0% 0%

With the portfolio, one could backtest the equity history as follows:

import pandas as pd
from finlab import backtest

position = pd.DataFrame({
    '2330': [0, 1, 1],
    '1101': [0.2, 0, 0],
    '2454': [0.4, 0, 0]
}, index=pd.to_datetime(['2021-12-31', '2022-03-31', '2022-06-30']))

report = backtest.sim(position)
Source code in finlab/backtest.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
def sim(position: Union[pd.DataFrame, pd.Series],
        resample:Union[str, None]=None, resample_offset:Union[str, None] = None,
        trade_at_price: Union[str, pd.DataFrame] = 'close',
        position_limit:float=1, fee_ratio:float=1.425/1000,
        tax_ratio: float=3/1000, name:str='未命名', stop_loss: Union[float, None]=None,
        take_profit: Union[float, None]=None, trail_stop: Union[float, None]=None, touched_exit: bool=False,
        retain_cost_when_rebalance: bool=False, stop_trading_next_period: bool=True, live_performance_start:Union[str, None]=None,
        mae_mfe_window:int=0, mae_mfe_window_step:int=1, market:Union[str, market_info.MarketInfo]='AUTO', upload:bool=True, fast_mode=False,
        notification_enable: bool=False, line_access_token: str='') -> report.Report:

    """Simulate the equity given the stock position history. 回測模擬股票部位所產生的淨值報酬率。

    Args:
        position (pd.DataFrame or pd.Series):
            買賣訊號紀錄。True 為持有, False 為空手。 若選擇做空position,只要將 sim(position) 改成負的 sim(-position.astype(float))即可做空。

        resample (str, None, pd.DataFrame, pd.Series, finlab.dataframe.FinlabDataFrame):
            交易週期。將 position 的訊號以週期性的方式論動股票,預設為每天換股。其他常用數值為 W、 M 、 Q (每週、每月、每季換股一次),也可以使用 W-Fri 在週五的時候產生新的股票清單,並且於下週交易日下單。

            * `D`: Daily
            * `W`: Weekly
            * `W-Wed`: Every Wednesday
            * `M`: Monthly
            * `MS`: Start of every month
            * `Q`: Quarterly
            * `QS`: Start of every quarter

            !!!note
                'D'與'None'的差別?
                resample='D' 的意義為每天隨股價變化做再平衡,就算當天股票清單沒變,但股票漲跌後,部位大小會變化,而 resample='D' 會強制再平衡,平均分散風險。

                但是當 resample=None 的話,假如清單不變,則不會強制再平衡,只有清單改變時,才做再平衡。適用情境在較常選到大波段標的的趨勢策略,較有機會將強勢股留下,而不會汰強留弱做再平衡。

            另外 `resample` 也接受 pd.DataFrame 以及 pd.Series,並且將其 index 用來當成換股的時間點,例如以下的範例:

            ``` py
            from finlab import backtest, data

            rev = data.get('monthly_revenue:當月營收')
            position = ...

            # 月營收發布時才換股
            backtest.sim(position, resample=rev)
            ```



        resample_offset (str or None):
            交易週期的時間位移,例如。

            - '1D': 位移一天
            - '1H': 位移一小時

        trade_at_price (str or pd.DataFrame):
            選擇回測之還原股價以收盤價或開盤價計算,預設為'close'。可選'close'、'open'、'open_close_avg'、'high_low_avg'或 'price_avg'。

        position_limit (float): maximum amount of investing a stock.
            單檔標的持股比例上限,控制倉位風險。預設為None。範例:0.2,代表單檔標的最多持有 20 % 部位。

        fee_ratio (float): fee ratio of buying or selling a stock.
            交易手續費率,預設為台灣無打折手續費 0.001425。可視個人使用的券商優惠調整費率。

        tax_ratio (float): tax ratio of selling a stock.
            交易稅率,預設為台灣普通股一般交易交易稅率 0.003。若交易策略的標的皆為ETF,記得設成 0.001。

        name (str): name of the strategy.
            策略名稱,預設為 未指名。策略名稱。相同名稱之策略上傳會覆寫。命名規則:全英文或開頭中文,不接受開頭英文接中文。

        stop_loss (float):
            停損基準,預設為None,不執行停損。範例:0.1,代表從再平衡開始,虧損 10% 時產生出場訊號。

        take_profit (float):
            停利基準,預設為None,不執行停利。範例:0.1,代表從再平衡開始, 10% 時產生出場訊號。

        trail_stop (float):
            移動停損停利基準,預設為None,不執行。範例:0.1,代表從最高點開始下跌,跌至 10% 時產生出場訊號。

        touched_exit (bool):
            是否在回測時,使用觸價停損停利?預設為 False。

        retain_cost_when_rebalance (bool):
            預設回測時,會將進場股票進場成本更新到到新的 rebalance 的當天價格,假如希望保留原本的進場價格當成停損停利的依據,可以設定為 `True`

        stop_trading_next_period (bool):
            當期已經停損停利,則下一期不買入,預設為 True。

        live_performance_start (str):
            策略建構的日期,例如 `2022-01-01` 此日期之前,策略未撰寫,此日期之後則視為與實單有類似效果,實際不影響回測的結果,單純紀錄而已。

        mae_mfe_window (int):
            計算mae_mfe於進場後於不同持有天數下的數據變化,主要應用為edge_ratio (優勢比率)計算。預設為0,則Report.display_mae_mfe_analysis(...)中的edge_ratio不會顯現。

        mae_mfe_window_step (int):
            與mae_mfe_window參數做搭配,為時間間隔設定,預設為1。若mae_mfe_window設20,mae_mfe_window_step設定為2,相當於python的range(0,20,2),以2日為間距計算mae_mfe。

        market (str or MarketInfo):
            可選擇`'TW_STOCK', 'CRYPTO'`,分別為台股或加密貨幣,
            或繼承 finlab.market_info.MarketInfo 開發回測市場類別。

        upload (bool):
            上傳策略至finlab網站,預設為True,上傳策略。
            範例: False,不上傳,可用 finlab.backtest.sim(position, upload=False, ...).display() 快速檢視策略績效。

        fast_mode (bool):
            預設為False,若設定為True,則會使用快速模式,快速模式會忽略所有的停利停損設定,並且只有換股日進行報酬率模擬,因此會有一些誤差,當持有較多檔股票時,可以大幅加速回測速度。

    Returns:
        (finlab.analysis.Report):回測數據報告

    Examples:
        Assume the history of portfolio is construct as follows: When market close on 2021-12-31, the portfolio {B: 0.2, C: 0.4} is calculated. When market close on 2022-03-31, the portfolio {A:1} is calculated.


        |            | Stock 2330 | Stock 1101 | Stock 2454 |
        |------------|------------|------------|------------|
        | 2021-12-31 | 0%         | 20%        | 40%        |
        | 2022-03-31 | 100%       | 0%         | 0%         |
        | 2022-06-30 | 100%       | 0%         | 0%         |


        With the portfolio, one could backtest the equity history as follows:

        ``` py
        import pandas as pd
        from finlab import backtest

        position = pd.DataFrame({
            '2330': [0, 1, 1],
            '1101': [0.2, 0, 0],
            '2454': [0.4, 0, 0]
        }, index=pd.to_datetime(['2021-12-31', '2022-03-31', '2022-06-30']))

        report = backtest.sim(position)
        ```

    """

    # check version
    check_version()

    if notification_enable == True and line_access_token == '':
        raise Exception('line_access_token is required when enabling notifications. Please provide a valid token.')

    if isinstance(position, FinlabDataFrame):
        position = position.index_str_to_date()

    if (trail_stop is not None or stop_loss is not None or take_profit is not None) and fast_mode:
        raise Exception('fast_mode cannot be used with trail_stop, stop_loss or take_profit.')

    # check type of position
    if not isinstance(position.index, pd.DatetimeIndex):
        raise TypeError("Expected the dataframe to have a DatetimeIndex")

    if isinstance(position, pd.Series) and position.name is None:
        raise Exception('Asset name not found. Please asign asset name by "position.name = \'2330\'".')

    # auto detect market type
    # todo: use less hacky method to identify the market
    market = get_market_info(position, user_market_info=market)

    if not isinstance(market, market_info.MarketInfo):
        raise Exception("It seems like the market has"
            "not been specified well when using the hold_until"
            " function. Please provide the market='TW', "
            "market='US' or market=MarketInfo")

    # determine trading price
    price = trade_at_price
    if isinstance(trade_at_price, str):
        price = market.get_trading_price(trade_at_price, adj=True)

    assert isinstance(price, pd.DataFrame)

    if isinstance(trade_at_price, pd.DataFrame) and touched_exit:
        print('**WARNING: Using trade_at_price as dataframe without high, and low price. Candle information is not completed.')
        print('           The backtest result can be incorrect when touched_exit=True.')
        print('           If the complete backtest result is required, please implement MarketInfo with get_price function.')
        print('           MarketInfo details: https://doc.finlab.tw/reference/market_info/')
        print('           And use backtest.sim(..., market=MarketInfo) during backtest, so that the correct information is accessable from backtest.sim().')

    try:
        if isinstance(live_performance_start, str):
            live_performance_start = datetime.datetime.fromisoformat(live_performance_start)
    except:
        raise Exception("**ERROR: live_performance_start string format not valid. It should be ISO format, i.e. YYYY-MM-DD.")


    high = price
    low = price
    open_ = price
    if touched_exit:
        high = market.get_price('high', adj=True).reindex_like(price)
        low = market.get_price('low', adj=True).reindex_like(price)
        open_ = market.get_price('open', adj=True).reindex_like(price)

    # check position types
    if isinstance(position, pd.Series):
        if position.name in price.columns:
            position = position.to_frame()
        else:
            raise Exception('Asset name not found. Please asign asset name by "position.name = \'2330\'".')

    # check position is valid
    # if position.abs().sum().sum() == 0 or len(position.index) == 0:
    #     raise Exception('Position is empty and zero stock is selected.')

    # format position index
    if isinstance(position.index[0], str):
        position = FinlabDataFrame(position).index_str_to_date()

    if not isinstance(position.index, pd.DatetimeIndex):
        raise Exception("The DataFrame index is not of type DatetimeIndex!")

    # if position date is very close to price end date, run all backtesting dates
    assert len(position.shape) >= 2
    delta_time_rebalance = position.index[-1] - position.index[-3]
    backtest_to_end = position.index[-1] + \
        delta_time_rebalance > price.index[-1]


    tz = position.index.tz
    now = datetime.datetime.now(tz=tz)

    # check if position date is daily (pd.Timestamp hour, minute, second is 0)
    is_daily = (position.index.hour == 0).all()\
        and (position.index.minute == 0).all()\
        and (position.index.second == 0).all()

    # set now to yesterday's end if is_daily position
    if is_daily and datetime.datetime.now(tz=market.tzinfo()) < market.market_close_at_timestamp():
        now = now.replace(hour=23, minute=59, second=0, microsecond=0) - datetime.timedelta(days=1)

    position = position[(position.index <= price.index[-1]) | (position.index <= now)]
    backtest_end_date = price.index[-1] if backtest_to_end else position.index[-1]

    # resample dates
    dates = None
    next_trading_date = position.index[-1]
    if isinstance(resample, pd.DataFrame) or isinstance(resample, pd.Series):

        if isinstance(resample.index, pd.DatetimeIndex):
            dates = resample.index.tolist()
        elif isinstance(resample, FinlabDataFrame):
            dates = resample.index_str_to_date().index.tolist()

        dates = [d for d in dates if position.index[0] <= d and d <= position.index[-1]]
        next_trading_date = dates[-1]

    elif isinstance(resample, pd.DatetimeIndex):

        dates = resample.tolist()
        dates = [d for d in dates if position.index[0] <= d and d <= position.index[-1]]
        next_trading_date = dates[-1]

    elif isinstance(resample, str):

        if pd.__version__ >= '3.0.0':
            old_resample_strings = ['M', 'BM', 'SM', 'CBM', 'Q', 'BQ', 'A', 'Y', 'BY']
            if resample in old_resample_strings:
                resample_str += 'E'

        # add additional day offset
        offset_days = 0
        if '+' in resample:
            offset_days = int(resample.split('+')[-1])
            resample = resample.split('+')[0]
        if '-' in resample and resample.split('-')[-1].isdigit():
            offset_days = -int(resample.split('-')[-1])
            resample = resample.split('-')[0]

        # generate rebalance dates
        alldates = pd.date_range(
            position.index[0],
            position.index[-1] + datetime.timedelta(days=720),
            freq=resample, tz=tz)

        alldates += DateOffset(days=offset_days)

        if resample_offset is not None:
            alldates += to_offset(resample_offset)

        dates = [d for d in alldates if position.index[0]
                 <= d and d <= position.index[-1]]

        # calculate the latest trading date
        next_trading_date = min(
           set(alldates) - set(dates))

        if dates[-1] != position.index[-1]:
            dates += [next_trading_date]

    elif resample is None:
        # user set resample to None. Rebalance everyday might cause over transaction.
        # remove rebalance date if portfolio is the same.
        change = (position.diff().abs().sum(axis=1) != 0) | ((position.index == position.index[0]) & position.iloc[0].notna().any())
        position = position.loc[change]

    if stop_loss is None or stop_loss == 0:
        stop_loss = 1

    if take_profit is None or take_profit == 0:
        take_profit = np.inf

    if trail_stop is None or trail_stop == 0:
        trail_stop = np.inf

    if dates is not None:
        position = position.reindex(dates, method='ffill')

    encryption = download_backtest_encryption()

    if encryption == '':
        raise Exception('Cannot perform backtest, permission denied.')

    args = arguments(price, high, low, open_, position, dates, fast_mode=fast_mode)

    creturn_value = backtest_(*args,
                              encryption=encryption,
                              fee_ratio=fee_ratio, tax_ratio=tax_ratio,
                              stop_loss=stop_loss, take_profit=take_profit, trail_stop=trail_stop,
                              touched_exit=touched_exit, position_limit=position_limit,
                              retain_cost_when_rebalance=retain_cost_when_rebalance,
                              stop_trading_next_period=stop_trading_next_period,
                              mae_mfe_window=mae_mfe_window, mae_mfe_window_step=mae_mfe_window_step)

    total_weight = position.abs().sum(axis=1).clip(1, None)

    position = position.div(total_weight.where(total_weight!=0, np.nan), axis=0).fillna(0)\
                       .clip(-abs(position_limit), abs(position_limit))


    creturn_dates = dates if dates and fast_mode else price.index

    creturn = (pd.Series(creturn_value, creturn_dates)
                # remove the begining of creturn since there is no pct change
                .pipe(lambda df: df[(df != 1).cumsum().shift(-1, fill_value=1) != 0])
                # remove the tail of creturn for verification
                .loc[:backtest_end_date]
                # replace creturn to 1 if creturn is None
                .pipe(lambda df: df if len(df) != 0 else pd.Series(1, position.index)))

    position = position.loc[creturn.index[0]:]

    price_index = args[4]
    position_columns = args[8]
    trades, operation_and_weight = get_trade_stocks(position_columns,
                                                    price_index, touched_exit=touched_exit)

    ####################################
    # refine mae mfe dataframe
    ####################################
    def refine_mae_mfe():
        mae_mfe_data = get_mae_mfe()
        if len(mae_mfe_data) == 0:
            return pd.DataFrame()

        m = pd.DataFrame(mae_mfe_data)
        nsets = int((m.shape[1]-1) / 6)

        metrics = ['mae', 'gmfe', 'bmfe', 'mdd', 'pdays', 'return']

        tuples = sum([[(n, metric) if n == 'exit' else (n * mae_mfe_window_step, metric)
                       for metric in metrics] for n in list(range(nsets)) + ['exit']], [])

        m.columns = pd.MultiIndex.from_tuples(
            tuples, names=["window", "metric"])
        m.index.name = 'trade_index'
        m[m == -1] = np.nan

        exit = m.exit.copy()

        if touched_exit and len(m) > 0 and 'exit' in m.columns:
            m['exit'] = (exit
                .assign(gmfe=exit.gmfe.clip(-abs(stop_loss), abs(take_profit)))
                .assign(bmfe=exit.bmfe.clip(-abs(stop_loss), abs(take_profit)))
                .assign(mae=exit.mae.clip(-abs(stop_loss), abs(take_profit)))
                .assign(mdd=exit.mdd.clip(-abs(stop_loss), abs(take_profit))))

        return m

    m = refine_mae_mfe()

    ####################################
    # refine trades dataframe
    ####################################
    def convert_datetime_series(df):
        cols = ['entry_date', 'exit_date', 'entry_sig_date', 'exit_sig_date']
        df[cols] = df[cols].apply(lambda s: pd.to_datetime(s).dt.tz_localize(tz))
        return df

    def assign_exit_nat(df):
        cols = ['exit_date', 'exit_sig_date']
        df[cols] = df[cols].loc[df.exit_index != -1]
        return df

    trades = (pd.DataFrame(trades,
                           columns=['stock_id', 'entry_date', 'exit_date',
                                    'entry_sig_date', 'exit_sig_date', 'position',
                                    'period', 'entry_index', 'exit_index'])
              .rename_axis('trade_index')
              .pipe(convert_datetime_series)
              .pipe(assign_exit_nat)
              )

    if len(trades) != 0:
        trades = trades.assign(**{'return': (1 - fee_ratio) * (m.iloc[:, -1]+1) * (1 - tax_ratio - fee_ratio) - 1})

        if touched_exit:
            min_return = (1 - fee_ratio) * (1 - abs(stop_loss)) * (1 - tax_ratio - fee_ratio) - 1
            max_return = (1 - fee_ratio) * (1 + abs(take_profit)) * (1 - tax_ratio - fee_ratio) - 1
            trades['return'] = trades['return'].clip(min_return, max_return)

    r = report.Report(
        creturn=creturn,
        position=position,
        fee_ratio=fee_ratio,
        tax_ratio=tax_ratio,
        trade_at=trade_at_price,
        next_trading_date=next_trading_date,
        market_info=market)

    r.resample = resample if isinstance(resample, str) else None
    r.stop_loss = stop_loss
    r.take_profit = take_profit
    r.trail_stop = trail_stop
    r.live_performance_start = live_performance_start

    r.mae_mfe = m

    r.trades = trades

    # calculate weights
    if len(operation_and_weight['weights']) != 0:
        r.weights = pd.Series(operation_and_weight['weights'])
        r.weights.index = r.position.columns[r.weights.index]
    else:
        r.weights = pd.Series(dtype='float64')


    # calculate next weights
    if len(operation_and_weight['next_weights']) != 0:
        r.next_weights = pd.Series(operation_and_weight['next_weights'])
        r.next_weights.index = r.position.columns[r.next_weights.index]
    else:
        r.next_weights = pd.Series(dtype='float64')


    # calculate actions
    if len(operation_and_weight['actions']) != 0:
        # find selling and buying stocks
        r.actions = pd.Series(operation_and_weight['actions'])
        r.actions.index = r.position.columns[r.actions.index]
    else:
        r.actions = pd.Series(dtype=object)


    # fill stock id to trade history
    snames = market.get_asset_id_to_name()
    f_id_to_name = lambda sid: f"{sid + ' ' + snames[sid] if sid in snames else sid}"
    if len(trades) != 0:
        r.trades['stock_id'] = r.trades.stock_id.map(f_id_to_name)

    if hasattr(r, 'actions') and len(r.actions) != 0:
        r.actions.index = r.actions.index.map(f_id_to_name)

    r.weights.index = r.weights.index.map(f_id_to_name)
    r.next_weights.index = r.next_weights.index.map(f_id_to_name)

    if len(r.actions) != 0:

        actions = r.actions

        sell_sids = actions[actions == 'exit'].index
        sell_instant_sids = actions[(actions == 'sl') | (actions == 'tp')
                                    | (actions == 'sl_enter') | (actions == 'tp_enter')].index
        buy_sids = actions[actions == 'enter'].index

        if len(trades):
            # check if the sell stocks are in the current position
            assert len(set(sell_sids) - set(trades.stock_id[trades.exit_sig_date.isnull()])) == 0

            # fill exit_sig_date and exit_date
            temp = trades.loc[trades.stock_id.isin(sell_sids), 'exit_sig_date'].fillna(r.position.index[-1])
            trades.loc[trades.stock_id.isin(sell_sids), 'exit_sig_date'] = temp

            temp = trades.loc[trades.stock_id.isin(sell_instant_sids), 'exit_sig_date'].fillna(price.index[-1])
            trades.loc[trades.stock_id.isin(sell_instant_sids), 'exit_sig_date'] = temp.to_numpy()

            r.trades = pd.concat([r.trades, pd.DataFrame({
              'stock_id': buy_sids.map(f_id_to_name),
              'entry_date': pd.NaT,
              'entry_sig_date': r.position.index[-1],
              'exit_date': pd.NaT,
              'exit_sig_date': pd.NaT,
            })], ignore_index=True)

            r.trades['exit_sig_date'] = pd.to_datetime(r.trades.exit_sig_date)

    r.add_trade_info('trade_price', market.get_trading_price(trade_at_price, adj=False), ['entry_date', 'exit_date'])
    if len(r.trades) != 0 and not fast_mode:
        r.run_analysis("Liquidity", display=False)

    # add mae mfe to report
    if len(trades) != 0:
        trades = r.trades
        mae_mfe = r.mae_mfe
        exit_mae_mfe = mae_mfe['exit'].copy()
        exit_mae_mfe = exit_mae_mfe.drop(columns=['return'])
        r.trades = pd.concat([trades, exit_mae_mfe], axis=1)
        r.trades.index.name = 'trade_index'

        # calculate r.current_trades
        # find trade without end or end today
        maxday = max(r.trades.entry_sig_date.max(), r.trades.exit_sig_date.max())
        latest_entry_day = r.trades.entry_sig_date[r.trades.entry_date.notna()].max()
        r.current_trades = r.trades[
                (r.trades.entry_sig_date == maxday )
                | (r.trades.exit_sig_date == maxday)
                | (r.trades.exit_sig_date >= latest_entry_day) # for the case of sl_enter, tp_enter
                | (r.trades.entry_sig_date == latest_entry_day)
                | (r.trades.exit_sig_date.isnull())]\
            .set_index('stock_id')# \

        # cannot drop duplicates, because the same stock can be traded multiple times
        # when a stock is exited and re-entered (tp_enter, sl_enter)
            # .pipe(lambda df: df[~df.index.duplicated(keep='last')])

        r.current_trades.loc[r.current_trades['return'].isna(), 'trade_price@entry_date'] = np.nan
        r.current_trades.loc[r.current_trades['return'].isna(), 'trade_price@exit_date'] = np.nan

        # r.next_trading_date = max(r.current_trades.entry_sig_date.max(), r.current_trades.exit_sig_date.max())

        r.current_trades['weight'] = 0
        if len(r.weights) != 0:
            r.current_trades['weight'] = r.weights.reindex(r.current_trades.index).fillna(0)

        r.current_trades['next_weights'] = 0
        if len(r.next_weights) != 0:
            r.current_trades['next_weights'] = r.next_weights.reindex(r.current_trades.index).fillna(0)

        if len(r.current_trades):
            r.current_trades.index = r.current_trades.index.map(f_id_to_name)

    if "pyodide" in sys.modules and "js" in sys.modules:
        set_global('backtest_report', {
            'report': r.to_json(),
            'position': r.position_info2()
            })

    if notification_enable:
        line_notify(r, line_access_token)

    if not upload:
        return r

    r.upload(name)
    return r

finlab.backtest.line_notify

line_notify(report=None, line_access_token='', test=False)

傳送回測結果之目前部位、近期換股訊息至Line聊天室。

PARAMETER DESCRIPTION
report

回測完的結果報告。

TYPE: Report DEFAULT: None

line_access_token

於Line Notify取得的access_token(權杖)。至Line Notify登入Line帳號後,點選個人頁面,點選「發行權杖」,選擇欲接收訊息的聊天室(可選擇1對1接收Line Notify通知、或是選擇其他群組聊天室),即可取得權杖。

TYPE: str DEFAULT: ''

test

是否進行傳送訊息測試。

TYPE: bool DEFAULT: False

Examples:

欲進行測試,則設定test參數為True。

from finlab import backtest

line_access_token = 'xxxxxxxxxxxx'
backtest.line_notify(line_access_token=line_access_token, test=True)

若成功收到通知,則權杖設定已完畢,可直接在sim回測模組中開啟使用,或單獨調用此函式發送回測換股訊息。 於sim中使用:

from finlab import backtest

line_access_token = 'xxxxxxxxxxxx'
position = ...
report = backtest.sim(position, notification_enable =True, line_access_token = line_access_token)

已回測完,單獨傳訊息用:

from finlab import backtest

line_access_token = 'xxxxxxxxxxxx'
report = backtest.sim(position)
backtest.line_notify(report, line_access_token=line_access_token)
Source code in finlab/backtest.py
def line_notify(report=None, line_access_token:str='', test:bool=False):
    """傳送回測結果之目前部位、近期換股訊息至Line聊天室。

    Args:
        report (Report):
            回測完的結果報告。

        line_access_token (str):
            於Line Notify取得的access_token(權杖)。至[Line Notify](https://notify-bot.line.me/zh_TW/ )登入Line帳號後,點選個人頁面,點選「發行權杖」,選擇欲接收訊息的聊天室(可選擇1對1接收Line Notify通知、或是選擇其他群組聊天室),即可取得權杖。
        test (bool):
            是否進行傳送訊息測試。

    Examples:
        欲進行測試,則設定`test`參數為True。

        ``` py
        from finlab import backtest

        line_access_token = 'xxxxxxxxxxxx'
        backtest.line_notify(line_access_token=line_access_token, test=True)
        ```

        若成功收到通知,則權杖設定已完畢,可直接在`sim`回測模組中開啟使用,或單獨調用此函式發送回測換股訊息。
        於sim中使用:

        ``` py
        from finlab import backtest

        line_access_token = 'xxxxxxxxxxxx'
        position = ...
        report = backtest.sim(position, notification_enable =True, line_access_token = line_access_token)
        ```

        已回測完,單獨傳訊息用:

        ``` py
        from finlab import backtest

        line_access_token = 'xxxxxxxxxxxx'
        report = backtest.sim(position)
        backtest.line_notify(report, line_access_token=line_access_token)
        ```

    """
    if test:
        message = 'Finlab line_notify 測試成功'
    else:
        if not isinstance(report, finlab.core.report.Report):
            raise Exception('Please provide a valid backtest report.')
        hold = []
        enter = []
        exit = []
        for i,p in report.position_info().items():
            if isinstance(p,dict):
                if i[:4].isdigit():
                    if p['status'] in ['exit'] and pd.isnull(report.current_trades.loc[i].exit_date):
                        hold.append(f"{i}: {p['entry_date'][:10]}, {str(p['entry_price'])}")
                    if p['status'] in ['hold','sl','tp']:
                        hold.append(f"{i}: {p['entry_date'][:10]}, {str(p['entry_price'])}")
                    if p['status'] in ['enter']:
                        enter.append(f"{i}: {p['entry_date'][:10]}的下個交易日進場")
                    if p['status'] in ['exit','sl','tp', 'sl_enter', 'tp_enter']:
                        exit.append(f"{i}: {p['exit_date'][:10]}的下個交易日出場")
        message_lines = ['目前策略清單 進場日及進場價格:']
        message_lines.extend(hold)
        message_lines.append('------------------------------')
        message_lines.append('近期操作:')
        message_lines.append('-策略新增')
        if len(enter) > 0:
            message_lines.extend(enter)
        else:
            message_lines.append('尚無')
        message_lines.append('-策略移除')
        if len(exit) > 0:
            message_lines.extend(exit)
        else:
            message_lines.append('尚無')
        message = "\n".join(message_lines)

    headers = {
        "Authorization": "Bearer " + line_access_token,
        "Content-Type" : "application/x-www-form-urlencoded"
        }
    r = requests.post("https://notify-api.line.me/api/notify", headers = headers, params = {'message': message})
    if test:
        if eval(r.text)['status'] == 401:
            print(f'測試失敗。{r.text}')
        elif eval(r.text)['status'] == 200:
            print('測試成功,可開始使用finlab line_notify')