DMA指标是一种趋势跟踪指标,它可以帮助我们判断股价的趋势以及股票的买卖时机。本文将使用Easytrader库,为大家介绍一种基于DMA指标的股票交易策略。
首先,我们需要导入所需的库:
import easytraderimport pandas as pdimport talibimport time
接下来,我们需要连接到我们的券商账户。这里以同花顺为例:
user = easytrader.use('ths')user.prepare('ths.json')
接下来,我们需要定义我们的交易策略:
code = '600519' # 股票代码ma_period = 20 # 均线周期dm_period = 14 # DMA指标周期buy_threshold = 0.3 # DMA指标买入阈值sell_threshold = -0.3 # DMA指标卖出阈值unit = 100 # 买入/卖出单位
然后,我们定义一个函数来获取股票历史数据:
def get_stock_data(code, ktype='D', start=None, end=None): df = pd.DataFrame(user.get_history_transaction_data(code, start_date=start, end_date=end)) df['datetime'] = pd.to_datetime(df['成交时间']) df.set_index('datetime', inplace=True) df.drop('成交时间', axis=1, inplace=True) df = df[['成交数量', '成交均价']] df.rename(columns={'成交数量': 'volume', '成交均价': 'close'}, inplace=True) df['open'] = df['close'] df['high'] = df['close'] df['low'] = df['close'] df = df.resample(ktype).apply({'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'volume': 'sum'}) df.dropna(inplace=True) return df
接着,我们定义一个函数来计算DMA指标并产生交易信号:
def generate_signals(df, ma_period, dm_period, buy_threshold, sell_threshold): df['high_ma'] = talib.SMA(df['high'], ma_period) df['low_ma'] = talib.SMA(df['low'], ma_period) df['dm_plus'] = talib.PLUS_DI(df['high'], df['low'], df['close'], dm_period) df['dm_minus'] = talib.MINUS_DI(df['high'], df['low'], df['close'], dm_period) df.dropna(inplace=True) df['signal'] = 0 for i in range(1, len(df)): if df['dm_plus'][i] > df['dm_minus'][i] and df['dm_plus'][i-1] <= df['dm_minus'][i-1]: df['signal'][i] = 1 elif df['dm_plus'][i] < df['dm_minus'][i] and df['dm_plus'][i-1] >= df['dm_minus'][i-1]: df['signal'][i] = -1 df['signal'] *= ((df['close'] - df['low_ma']) / df['close']) # 加入离均差因素 df['signal'].ffill(inplace=True) df['signal'].iloc[:ma_period] = 0 df['buy'] = (df['signal'] >= buy_threshold) df['sell'] = (df['signal'] <= sell_threshold) return df[['buy', 'sell', 'close']]
最后,我们定义主函数,用于实现交易逻辑:
def run(code, ma_period, dm_period, buy_threshold, sell_threshold, unit): while True: df = get_stock_data(code) signals = generate_signals(df, ma_period, dm_period, buy_threshold, sell_threshold) if signals['buy'][-1]: user.buy(code, price=df['close'][-1], amount=unit) print('买入', code, unit, '股') elif signals['sell'][-1]: user.sell(code, price=df['close'][-1], amount=unit) print('卖出', code, unit, '股') time.sleep(60)if __name__ == '__main__': run
联系客服