# 月營收成長率策略應用

## 前言

1. 進場條件：mom大於10月mom平均且yoy大於5月yoy平均
2. 出場條件：mom小於10月mom平均且yoy小於5月yoy平均

## 編輯環境及模組需求

```import pandas as pd
import numpy as np
import tejapi
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms
from matplotlib.font_manager import FontProperties
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS'] # 解決MAC電腦 plot中文問題
plt.rcParams['axes.unicode_minus'] = False
tejapi.ApiConfig.ignoretz = True```

## 資料導入

```data=tejapi.get('TWN/ANPRCSTD' ,chinese_column_name=True )
select=data["上市別"].unique()
select=select[1:3]
condition =(data["上市別"].isin(select)) & ( data["證券種類名稱"]=="普通股" )
data=data[condition]
twid=data["證券碼"].to_list()  #取得上市櫃股票證券碼```
```def get_data(code:str, id_):
df = tejapi.get(code, #從TEJ api撈取所需要的資料
chinese_column_name = True,
paginate = True,
mdate = {'gt':'2013-04-01', 'lt':'2021-12-31'},
coid=id_,
return df```
```def get_data1(code:str, id_):
df = tejapi.get(code, #從TEJ api撈取所需要的資料
chinese_column_name = True,
paginate = True,
mdate = {'gt':'2013-04-01', 'lt':'2021-12-31'},
coid=id_,
opts={'columns':['coid','annd_s', 'd0003', 'd0004']})
return df```

```df_1 = get_data('TWN/APRCD1', i)
df = get_data1('TWN/ASALE', i)
df.rename(columns={'營收發布日':'年月日','單月營收成長率%':'yoy', '單月營收與上月比%':'mom', '公司':'證券代碼'}, inplace=True)
df['yoy3'] = df['yoy'].rolling(5).mean()
df['mom3'] = df['mom'].rolling(10).mean()```
```df2 = df_1.merge(df, on=['證券代碼', '年月日'], how='outer')
df2 = df2.sort_values(by='年月日')
df2[['yoy', 'mom','yoy3','mom3']] = df2[['yoy', 'mom','yoy3',"mom3"]].shift(1)
df3 = df2.dropna()
df3.set_index(df3['年月日'], inplace=True)
df3.drop(columns={'年月日'}, inplace=True)```

```for i in range(len(data)):

if  (data["yoy"][i] > data["yoy3"][i]) & (data["mom"][i] > data["mom3"][i]):
sell.append(np.nan)
if hold !=1:

hold = 1
else:
elif (data["yoy"][i] < data["yoy3"][i]) & (data["mom"][i] < data["mom3"][i]):
if hold !=0:
sell.append(data["收盤價(元)"][i])
hold = 0
else:
sell.append(np.nan)
else:
sell.append(np.nan)

```qq = pd.DataFrame()
for i in twid[:]:
df_1 = get_data("TWN/APRCD1",i)
df = get_data1("TWN/ASALE",i)
df.rename(columns={'營收發布日':'年月日','單月營收成長率%':'yoy', '單月營收與上月比%':'mom', '公司':'證券代碼'}, inplace=True)
df['yoy3'] = df['yoy'].rolling(5).mean()
df['mom3'] = df['mom'].rolling(10).mean()
df2 = df_1.merge(df, on=['證券代碼', '年月日'], how='outer')
df2 = df2.sort_values(by='年月日')
df2[['yoy', 'mom','yoy3','mom3']] = df2[['yoy', 'mom','yoy3',"mom3"]].shift(1)
df3 = df2.dropna()
df3.set_index(df3['年月日'], inplace=True)
df3.drop(columns={'年月日'}, inplace=True)
print(i)
qq.index.name = '證券碼'```

```print(qq.isna().sum())
qq.dropna(inplace=True)```

```print('勝率：',qq['勝率'].mean())
print('報酬率：',qq['報酬'].mean())```

```qq['count'] = np.where( (qq['報酬']>0) &(qq['勝率']>= 50),1,0)
(qq['count'].sum()/qq['count'].count())*100```

```qq['20%'] = np.where((qq['勝率']>= 80),1,0)
qq['40%'] = np.where((qq['勝率']>= 60)& (qq['勝率']< 80),1,0)
qq['60%'] = np.where((qq['勝率']>= 40)& (qq['勝率']< 60),1,0)
qq['80%'] = np.where((qq['勝率']>= 20)& (qq['勝率']< 40),1,0)
qq['100%'] = np.where((qq['勝率']<20),1,0)
z5 = [qq['20%'].sum(),qq['40%'].sum(), qq['60%'].sum(), qq['80%'].sum(),qq['100%'].sum()]```

```plt.figure(figsize=(8,10))
plt.pie(z5,
labels=['勝率>80%','80%>勝率>60%','60%>勝率>40%','40%>勝率>20%','勝率<20%'],
autopct='%.1f%%',    # %.1f%% 表示顯示小數點一位的浮點數，後方加上百分比符號
pctdistance = 0.6,
textprops = {"fontsize" : 18})  # 文字大小)
plt.title('月營收成長率策略勝率佔比', {"fontsize":18})
plt.legend(loc = "best")
plt.axis('equal')

plt.show()```

Procesing