簡單的交易程式

邏輯是參考選擇一個優質股,然後以一定的倉位做波段,選擇的是長期持股的策略,原則是跌了買,反彈了則賣出相應的加倉。。。留有底倉最佳,選擇的版塊推薦是消費+醫藥

之前一直是想後面做一個程式化對股票資料做清洗篩選,然後形成一個交易策略,最終做到自動化交易

期間少不了無數的回測和修正

出差時候,遠離了家裡的電腦遊戲,才沉下來開始寫,小有收穫,但是發現選取的資料庫存在資料缺失,不失為一個大的遺憾,後面看如何去彌補這個

本以為有一個很好的回測結果,但是資料缺失的話,所以計算出的結果,不具備參考性,但是可以在這個基礎上不斷去最佳化日內分時,然後選擇一個策略

原始碼:

importtushareasts

importpandasaspd

importdatetime

token =‘fc087ee503a6feac6cf5dde3e409dc44613d395bab12a4c4470707a4’

pro = ts。pro_api(token)

pd。set_option(‘display。width’,1000)#顯示所有列,從左至右,不隱藏

pd。set_option(‘display。max_columns’, None)#顯示所有列,可能會隱藏中間

pd。set_option(‘display。max_rows’, None)

trade_count = [,]#初始化記錄買入次數,並新增

#建立一個空dataframe用來新增買的股的記錄

buy_df = pd。DataFrame(columns=[‘date’,‘buy_price’,‘hands’,‘expends’])

sell_df = pd。DataFrame(columns=[‘date’,‘sell_price’,‘hands’,‘expends’])

BS_df = pd。DataFrame(columns=[‘date’,‘BS_time’,‘price’,‘hands’,‘amount’,‘BS’])

total_account = [0。0,50000。0,50000。0]#股票+可用=總餘額

# print(BS_df)

defstrategy1(code,trade_date,buy_df,sell_df,BS_df,total_account,trade_count):

df1 = ts。get_hist_data(code,start=trade_date,end=trade_date)#前復權

df2 = ts。get_tick_data(code,date=trade_date,alt="簡單的交易程式" data-isLoading="0" src="/static/img/blank.gif" data-src=‘tt’)

#需要判斷是否股票當天有交易,開始or停牌

if(df1。size >):

trade_count[] = trade_count[] +1

ifdf2is None:

trade_count[1] = trade_count[1] +1

print(‘是交易日但是抓取不到當日分時資料……’)

#初始化引數

total_expend =0。0

total_income =0。0

buy_count =#初始化記錄買入次數,並新增

sell_count = buy_df[‘hands’]。sum()#初始化記錄買入次數,並新增

trade_date = df1。index[]

price_change = df1[‘price_change’][]

close = df1[‘close’][]

pre_close = close - price_change

ma5= df1[‘ma5’][]

ma10= df1[‘ma10’][]

ma20= df1[‘ma20’][]

open = df2[‘price’]。iloc[]

close = df2[‘price’]。iloc[-1]

open_change= (open - pre_close)/pre_close*100

close_change= (close - pre_close)/pre_close*100

forbuyindf2。values:

#計算漲跌幅

i = buy[1]

BS_time = buy[]

change =round((i - pre_close)/pre_close*100,2)

#買入程式判斷

stock_account = sell_count*i*100

ifstock_account/(total_account[2] +1。0)

if(change < -3。2)and(buy_count

buy_count = buy_count +1#買入次數

expend =round(i*300*(1。0+3。0/10000),2)

buy_df = buy_df。append(pd。DataFrame({‘date’: trade_date,‘buy_price’: i,‘hands’:3,‘expends’: expend},index=[]),ignore_index=True)

total_expend = expend + total_expend#計算當日總支出

total_expend =round(float((total_expend +0。000001) *100) /100。0,2)

total_count = buy_df[‘hands’]。sum()

daily_change = total_income - total_expend

total_account[] = total_count * close *100

total_account[] =round(total_account[],2)

total_account[1] = total_account[1] + daily_change

total_account[1] =round(total_account[1],2)

total_account[2] = total_account[] + total_account[1]

total_account[2] =round(total_account[2],2)

BS_df = BS_df。append(pd。DataFrame(

{‘date’: trade_date,‘BS_time’: BS_time,‘price’: i,‘hands’:3,‘amount’: -expend,‘BS’:‘B’},

index=[]),ignore_index=True)

print(‘買入條件1觸發…………’,i,change,buy_count,expend,total_account[2])

if(change < -6。2)and(buy_count

buy_count = buy_count +1#新買入手數

expend = i*100*(1。0+3。0/10000)

buy_df = buy_df。append(pd。DataFrame(

{‘date’: trade_date,‘buy_price’: i,‘hands’:1,‘expends’: expend},index=[]),ignore_index=True)

total_expend =round(float((total_expend +0。000001) *100) /100。0,2)

total_count = buy_df[‘hands’]。sum()

daily_change = total_income - total_expend

total_account[] = total_count * close *100

total_account[] =round(total_account[],2)

total_account[1] = total_account[1] + daily_change

total_account[1] =round(total_account[1],2)

total_account[2] = total_account[] + total_account[1]

total_account[2] =round(total_account[2],2)

BS_df = BS_df。append(pd。DataFrame(

{‘date’: trade_date,‘BS_time’: BS_time,‘price’: i,‘hands’:3,‘amount’: -expend,‘BS’:‘B’},

index=[]),ignore_index=True)

print(‘買入條件2觸發…………’,i,change,buy_count,expend,total_account[2])

if(change < -9。2)and(buy_count

buy_count = buy_count +1#新買入手數

expend = i*100*(1。0+3。0/10000)

buy_df = buy_df。append(pd。DataFrame(

{‘date’: trade_date,‘buy_price’: i,‘hands’:1,‘expends’: expend},index=[]),ignore_index=True)

total_expend =round(float((total_expend +0。000001) *100) /100。0,2)

total_count = buy_df[‘hands’]。sum()

daily_change = total_income - total_expend

total_account[] = total_count * close *100

total_account[] =round(total_account[],2)

total_account[1] = total_account[1] + daily_change

total_account[1] =round(total_account[1],2)

total_account[2] = total_account[] + total_account[1]

total_account[2] =round(total_account[2],2)

BS_df = BS_df。append(pd。DataFrame(

{‘date’: trade_date,‘BS_time’: BS_time,‘price’: i,‘hands’:3,‘amount’: -expend,‘BS’:‘B’},

index=[]),ignore_index=True)

print(‘買入條件3觸發…………’,i,change,buy_count,expend,total_account[2])

#賣出程式判斷,遍歷買入記錄做判斷

ifstock_account / (total_account[2] +1。0) >=0。01:#大於0。5總賬戶才能夠賣出股票

forsellinbuy_df。values:

j = sell[1]

ifsell[] < trade_date:#只有時間比今天小的才能賣出去

if(i - j)/j >0。03and(sell_count >):

sell_count = sell_count -1

buy_df = buy_df[~buy_df[‘buy_price’]。isin([j])]

income = i*300*(1。0+1。0/1000+3。0/10000)

total_income = income + total_income

total_count = buy_df[‘hands’]。sum()

daily_change = total_income - total_expend

total_account[] = total_count * close *100

total_account[] =round(total_account[],2)

total_account[1] = total_account[1] + daily_change

total_account[1] =round(total_account[1],2)

total_account[2] = total_account[] + total_account[1]

total_account[2] =round(total_account[2],2)

sell_df = sell_df。append(pd。DataFrame(

{‘date’: trade_date,‘sell_price’: j,‘hands’:3,‘expends’: income},index=[]),ignore_index=True)

BS_df = BS_df。append(pd。DataFrame(

{‘date’: trade_date,‘BS_time’: BS_time,‘price’: i,‘hands’:3,‘amount’: income,‘BS’:‘S’},

index=[]),ignore_index=True)

print(‘賣出條件觸發…………’,sell[],trade_date,i,j,sell_count)

# return pre_close,open,open_change,close_change,ma5,ma10,ma20

returnbuy_df。round(2),sell_df。round(2),BS_df。round(2),total_account,trade_count

code =‘002773’

begin = datetime。date(2019,6,24)

end = datetime。date(2020,6,6)

foriinrange((end - begin)。days +1):

day = begin + datetime。timedelta(days=i)

trade_date = day。strftime(‘%Y-%m-%d’)

try:

buy_df,sell_df,BS_df,total_account,trade_count = strategy1(code,trade_date,buy_df,sell_df,BS_df,total_account,trade_count)

# print(buy_df,sell_df,BS_df,total_account)

print(‘今天是交易日:’,trade_date)

print(BS_df,total_account,trade_count,sep=‘\n’)

except:

print(‘不存在交易……。。’)

執行的結果:

今天是交易日: 2020-06-05

date   BS_time  price hands    amount BS

0   2019-08-21  14:34:52  32。90     3  -9872。96  B

1   2019-08-26  09:25:05  34。96     3  10501。63  S

2   2019-10-24  09:38:57  32。91     3  -9875。96  B

3   2019-10-28  09:32:39  33。97     3  10204。25  S

4   2019-10-31  09:30:04  30。38     3  -9116。73  B

5   2019-11-05  09:25:05  31。40     3   9432。25  S

6   2019-11-13  13:32:48  30。16     3  -9050。71  B

7   2019-11-14  09:30:37  31。08     3   9336。12  S

8   2019-12-02  09:32:45  38。50     3 -11553。47  B

9   2019-12-04  09:30:58  39。70     3  11925。48  S

10  2020-02-03  09:25:04  34。91     3 -10476。14  B

11  2020-02-03  09:25:04  34。91     3  -3492。05  B

12  2020-02-04  10:06:10  35。96     3  10802。02  S

13  2020-02-04  10:06:10  35。96     3  10802。02  S

14  2020-02-26  14:54:10  34。00     3 -10203。06  B

15  2020-02-28  10:25:43  33。33     3 -10002。00  B

16  2020-03-02  11:09:52  34。35     3  10318。40  S

17  2020-03-02  13:07:22  35。04     3  10525。67  S

18  2020-03-09  09:47:52  35。53     3 -10662。20  B

19  2020-03-10  09:25:01  37。00     3  11114。43  S

20  2020-03-10  10:42:28  35。18     3 -10557。17  B

21  2020-03-11  09:30:13  36。38     3  10928。19  S

22  2020-03-13  09:25:04  33。87     3 -10164。05  B

23  2020-03-16  09:25:02  35。72     3  10729。93  S

24  2020-03-17  10:08:37  34。34     3 -10305。09  B

25  2020-03-18  09:30:07  35。50     3  10663。84  S

26  2020-03-19  13:07:41  34。81     3 -10446。13  B

27  2020-03-20  09:25:01  35。93     3  10793。01  S

28  2020-03-30  10:08:25  39。00     3 -11703。51  B

29  2020-04-01  11:28:46  38。11     3 -11436。43  B

30  2020-04-03  10:21:01  39。30     3  11805。33  S

31  2020-04-03  10:45:49  40。19     3  12072。67  S

32  2020-04-10  13:30:58  40。70     3 -12213。66  B

33  2020-05-11  13:21:19  38。73     3 -11622。49  B

[22902。0, 76257。52, 99159。52]

[233, 105]

總共期間交易日存在233,但是日內資料分時缺失高達105次,所以產生的交易是不完全的,不能拿來參考

最終持倉22902,可用餘額76257,總金額從初始的5W上升到99159

因此換個角度,在一個震盪的區間股,一年操作了33次,也產生了可觀的收益!

共勉~~

其實也嘗試做了分時圖顯示,不過python自帶的畫圖工具好像不太好用,自己也不是很熟悉,後面再擇機看如何做,需要大神一起最佳化速度或許更快~

簡單的交易程式

好久沒寫帖子,水一下~