# 資金管理

## 編輯環境及模組需求

``import matplotlib.pyplot as plt` `import numpy as np` `import tejapi` `tejapi.ApiConfig.api_key = "your key"``

## 資料處理

``data_return = tejapi.get('TWN/AAPRCM1',` `                         coid = '0050',` `                         mdate= {'gte': '2010-01-01','lte':'2015-12-31'},` `                         opts={'columns':['coid','mdate','roi']},` `                         chinese_column_name=True,paginate=True)``

## 凱利公式

• 勝率Ｐ：成功的總次數/（成功的總次數+失敗的總次數）
• 賠率ｂ：成功時的盈利/失敗時的虧損
• 下注比例ｆ：投入資金占本金的比例
``data_return['勝率'] = np.where(data_return['報酬率％_月'] >= 0 ,1,0)` `data_return['勝率'] = data_return.rolling(12)['勝率'].sum() / 12` `data_return['獲利'] = np.where(data_return['報酬率％_月'] >= 0 ,data_return['報酬率％_月'],np.nan)` `data_return['虧損'] = np.where(data_return['報酬率％_月'] < 0 ,data_return['報酬率％_月'],np.nan)` `data_return['賠率'] = data_return.rolling(12, min_periods=1)['獲利'].mean()/ data_return.rolling(12, min_periods=1)['虧損'].mean().abs()``

````data_return['下注比例'] = ` `    np.where(data_return['勝率'] * data_return['賠率'] - (1 - data_return['勝率']) < 0,0,` `             (data_return['勝率'] * data_return['賠率'] - (1 - data_return['勝率'])) / data_return['賠率']` `             )` ```# 前一個月的下注比例，避免前視偏誤
data_return['下注比例'] = data_return['下注比例'].shift()``````

``for i in range(0,len(data_return)):` `    if i == 0:` `        data_return['buy & hold本金'] = 1000000 # 起始本金` `    else:` `        data_return.loc[i,'buy & hold本金'] = 1000000 * data_return.loc[i-1,'累積報酬率％_月']` `for i in range(0,len(data_return)):` `    if i == 0:` `        data_return['凱利本金'] = 1000000 # 起始本金` `    else:` `        if data_return.loc[i,'下注比例'] > 0:` `            data_return.loc[i,'凱利本金'] = data_return.loc[i-1,'凱利本金'] * (1 - data_return.loc[i,'下注比例']) ` `                + data_return.loc[i-1,'凱利本金'] * data_return.loc[i,'下注比例'] * (1 + data_return.loc[i,'報酬率％_月']) ` `                    # - data_return.loc[i-1,'凱利本金'] * data_return.loc[i,'下注比例'] * 0.002 # 手續費` `        else:` `            data_return.loc[i,'凱利本金'] = data_return.loc[i-1,'凱利本金']``

Procesing