全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 python论坛
2006 2
2017-10-07


import tushare as tsi
mport pandas as pd
import matplotlib.pyplot as plt
MA_S = 3
MA_L = 25
trade_fee = 0.001
sell_v = 0.18
hold_v = 0
buy_v = -0.25
interest_rate = 0.02/365
stock = '399006&# 39;
df = ts.get_h_data(stock, start='2010-06-01&# 39;, end=pd.datetime.now().strftime("%Y-%m-%d"), index=True)
#df = ts.get_h_data(stock, index=True)
df = df.sort_index(ascending=True)
close = df[&# 39;close']
MA_short = pd.rolling_mean(close,MA_S)
MA_long = pd.rolling_mean(close,MA_L)
BIAS = MA_short/MA_long - 1
RSI_1 = sell_v - BIAS[BIAS>sell_v]
BIAS_Temp = BIAS[BIAS<=sell_v]RSI_2 =
sell_v - BIAS_Temp[BIAS_Temp>(sell_v+hold_v)/2]
BIAS_Temp = BIAS_Temp[BIAS_Temp<=(sell_v+hold_v)/2]
RSI_3 = BIAS_Temp[BIAS_Temp>hold_v] - hold_v
BIAS_Temp = BIAS_Temp[BIAS_Temp<=hold_v]
RSI_4 = BIAS_Temp[BIAS_Temp>(hold_v+buy_v)/2] - hold_v
BIAS_Temp = BIAS_Temp[BIAS_Temp<=(hold_v+buy_v)/2]
RSI_5 = buy_v - BIAS_Temp[BIAS_Temp>buy_v]
BIAS_Temp = BIAS_Temp[BIAS_Temp<=buy_v]
RSI_6 = buy_v - BIAS_TempRSI = pd.Series(RSI_1)
RSI = RSI.append(RSI_2)
RSI = RSI.append(RSI_3)
RSI = RSI.append(RSI_4)
RSI = RSI.append(RSI_5)
RSI = RSI.append(RSI_6)
df2 = pd.DataFrame(close)
df2[&# 39;MA'+str(MA_S)] = MA_short
df2[&# 39;MA' + str(MA_L)] = MA_long
df2[&# 39;BIAS'] = BIAS
df2[&# 39;RSI'] = RSI
df2[&# 39;Positions'] = df2.RSI > 0
se = pd.Series(df2[&# 39;Positions'])
BS = [&# 39;BLANK',&# 39;BLANK']
NetWorth = [1, 1*(1 + interest_rate)]
idx = 1
while (idx < se.size - 1):   
  idx = idx + 1   
  if (se[idx - 1]!=se[idx-2]):        
   if (se[idx - 1]==True):            
     BS.insert(idx, &# 39;BUY')            
     NetWorth.insert(idx, NetWorth[idx - 1]*(1-trade_fee + interest_rate))        
    else:            
      BS.insert(idx, &# 39;SELL')            
      NetWorth.insert(idx, NetWorth[idx - 1]*(1 + (close[idx]-close[idx - 1])/close[idx - 1])*(1-trade_fee))   
      else:        
      if (se[idx - 1]==True):            
       BS.insert(idx, &# 39;HOLD')            
       NetWorth.insert(idx, NetWorth[idx - 1]*(1 + (close[idx]-close[idx - 1])/close[idx - 1]))        
     else:            
       BS.insert(idx, &# 39;BLANK')            
      NetWorth.insert(idx, NetWorth[idx - 1]*(1 + interest_rate))
       BS_series = pd.Series(BS, index=se.index)
       NetWorth_series = pd.Series(NetWorth, index=se.index)
      df2[&# 39;BS'] = BS_seriesdf2[&# 39;NetWorth'] = NetWorth_series   
      df2.to_excel("test.xlsx",sheet_name=&# 39;Sheet1')
       of = 1000
      # plt.figure(figsize=(60,30), dpi=8)
      plt.plot(NetWorth_series[-250:]*of,  label="Net Workth")
      plt.plot(close[-250:], label="Close Price")
      #plt.plot(MA_short, label=&# 39;MA'+str(MA_S))
      # plt.plot(MA_long, label='MA&# 39;+str(MA_L))
      plt.legend(loc='upper left&# 39;, frameon=False)
      Buy_Sell_Point = BS_series[BS_series=='BUY&# 39;]
      Buy_Sell_Point = Buy_Sell_Point.append(BS_series[BS_series=='SELL&# 39;])
      Buy_Sell_Point = Buy_Sell_Point.sort_index(ascending=True)
       idx = 0
       last_annotate_idx = 0
       ytext = 20
       gain_count = 0
       sell_count = 0
       gain_sum = 0
      print("\n")
      bs_data = pd.DataFrame(index=Buy_Sell_Point.index, columns=
                 ['index&# 39;,'type&# 39;,'networth&# 39;,'gain&# 39;])
     while (idx < Buy_Sell_Point.size):   
      xz = Buy_Sell_Point.index[idx]   
      yz = close[xz]   
      nw = NetWorth_series[xz]   
       nw_of = nw*of   
       nw2 = round(nw, 4)   
       ptext = str(xz) + "  " + str(idx + 1) + " " + Buy_Sell_Point[idx] + "  " + str(nw2)   
      bs_data.ix[xz] = [idx + 1,Buy_Sell_Point[idx],nw2,0]   
      bsText = "B"   
      bsColor = 'red&# 39;   
       gain2 = 0   
      if (Buy_Sell_Point[idx]=='SELL&# 39;):        
      sell_count = sell_count + 1        
      bsText = "S"        
      bsColor = 'green&# 39;        
      gain = (nw - NetWorth_series[Buy_Sell_Point.index[idx - 1]])        
      gain_sum = gain_sum + gain      
       gain2 = round(gain, 4)      
         bs_data.ix[xz,'gain&# 39;] = gain2      
         ptext = ptext + "  " + str(gain2)      
         if (gain > 0):            
           gain_count = gain_count + 1               
           if (idx > 0 and ((pd.datetime.now() - xz).days < 365)):        
             yz_last = close[Buy_Sell_Point.index[last_annotate_idx]];        
           if ((abs(yz - yz_last)/yz_last) > 0.1 or (xz - Buy_Sell_Point.index[last_annotate_idx]).days > 20):           
            ytext = 20            
             plt.annotate(str(nw2), xy=(xz, nw_of), xycoords='data&# 39;,
                     xytext=(+10, ytext), textcoords='offset points&# 39;,
                      fontsize=10, arrowprops=dict(arrow, connection))            
             plt.annotate(round(yz), xy=(xz, yz), xycoords='data&# 39;,
          xytext=(-10, 0-ytext), textcoords='offset points&# 39;,
             fontsize=10, arrowprops=dict(arrow, connection))           
          if (bsText == "S"):               
             plt.annotate(str(gain2), xy=(xz, nw_of), xycoords='data&# 39;,
              xytext=(-10, 0-ytext), textcoords='offset points&# 39;,
                     fontsize=10, arrowprops=dict(arrow, connection))         
                         yzt = yz         
             if (nw_of > yz):               
                    yzt = nw_of           
                plt.plot([xz,xz], [500,yzt], color='yellow&# 39;,line)         
                plt.annotate(bsText + str(idx + 1), xy=(xz, yz), xycoords='data&# 39;,
                    xytext=(+10, ytext), textcoords='offset points&# 39;,
                    fontsize=10, arrowprops=dict(arrow, connection))                       
                   last_annotate_idx = idx        
               else:            
                     ytext = ytext + 20           
                       plt.scatter(xz, yz, 30, color =bsColor)      
                      plt.scatter(xz, nw_of, 30, color =bsColor)         
                       idx = idx + 1   
                       #print(ptext)print("BUY_SELL: " + str(sell_count) + "    " + "GAIN: " + str(gain_count) + "    "
                       + "SUM: " + str(round(gain_sum,4)))bs_data = bs_data.sort_values(&# 39;gain',ascending=False)
                        print(bs_data)bs_data.to_excel("test2.xlsx",sheet_name=&# 39;Sheet1')ax = plt.gca()ax.spines[&# 39;
                       bottom'].set_position((&# 39;data',500))for label in ax.get_xticklabels() + ax.get_yticklabels():
                   label.set_fontsize(16)   
                 label.set_bbox(dict(facecolor=&# 39;white', edgecolor=&# 39;None', alpha=0.65 ))
                 plt.show()

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
有些语句分成多行显示,直接编译可能无法通过,敬请留意重新自行编辑。


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2017-10-12 17:21:17
试一下
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2017-10-13 08:22:15
感谢分享,点赞
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群