Skip to content

Instantly share code, notes, and snippets.

@lookis
Created November 6, 2017 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lookis/ce0c2391f375547ae084e15c24c4469e to your computer and use it in GitHub Desktop.
Save lookis/ce0c2391f375547ae084e15c24c4469e to your computer and use it in GitHub Desktop.
import pandas as pd
import numpy as np
import talib
import tushare as ts
import datetime
def timing(df):
r = []
for index, row in df.iterrows():
if(index != len(df.index) - 1 and (row['low'] < df.iloc[[index + 1]]['low']).tolist()[0] and (row['high'] > df.iloc[[index + 1]]['high']).tolist()[0]):
df.at[index + 1, 'open'] = row['open']
df.at[index + 1, 'close'] = row['close']
df.at[index + 1, 'low'] = row['low']
df.at[index + 1, 'high'] = row['high']
# MA40
ma = talib.SMA(np.array(df['close'].tolist()), timeperiod=40)
# strategy
holding = False
for index, row in df.iterrows():
if(not holding and not np.isnan(ma[index]) and index > 0 and (df.iloc[[index - 2]]['close'] < ma[index - 2]).tolist()[0] and (df.iloc[[index - 1]]['close'] > ma[index - 1]).tolist()[0] and (df.iloc[[index]]['close'] > ma[index]).tolist()[0] and ((df.iloc[[index]]['low'].tolist()[0] < df.iloc[[index - 1]]['low'].tolist()[0]) or (df.iloc[[index]]['high'].tolist()[0] > df.iloc[[index - 1]]['high'].tolist()[0]))):
r.append((row['date'], 'BUY'))
holding = True
if(holding and not np.isnan(ma[index]) and index > 1 and (df.iloc[[index - 2]]['close'] > ma[index - 2]).tolist()[0] and (df.iloc[[index - 1]]['close'] < ma[index - 1]).tolist()[0] and (df.iloc[[index]]['close'] < ma[index]).tolist()[0] and ((df.iloc[[index]]['low'].tolist()[0] < df.iloc[[index - 1]]['low'].tolist()[0]) or (df.iloc[[index]]['high'].tolist()[0] > df.iloc[[index - 1]]['high'].tolist()[0]))):
r.append((row['date'], 'SELL'))
holding = False
return r
def prt(name, code):
print('================================')
df = ts.get_k_data(code=code, index=True)
print('Timing for ' + name)
print('================================')
for idx, data in enumerate(timing(df)):
if (idx % 2 == 0):
print('')
print(data, end='\t', flush=True)
print('')
print('')
print('请于当日K线数据更新之后运行, 指导下一个交易日的操作')
print('今天是:' + datetime.date.today().isoformat())
prt('SH50', '000016')
prt('HS300', '000300')
prt('ZZ500', '399905')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment