根据当前和之前的时间段创建信号

时间:2018-03-06 15:43:02

标签: python trading

我试图写一个交易算法,我对python很新。

很多事情很容易理解,但我很容易迷失方向。我有一个我想要使用的策略,但编码正在阻碍。

我想创建两个移动平均线,当它们交叉时,我希望它是一个信号。

我目前正在努力解决的问题还包括前一时期的信息。


MovingAverage1( last 10 candles ) == MovingAverage2( Last 20 candles )
这是一个信号,
但它是买还是卖?


MovingAVerage1( last 10 candles after skipping most recent ) > MovingAverage2( last 10 candles after skipping most recent )
然后卖掉。

这是我到目前为止所获得的,我正在使用的MA-s正在简化这个问题:

class MyMACrossStrategy (Strategy):
    """    
    Requires:
    symbol - A stock symbol on which to form a strategy on.
    bars - A DataFrame of bars for the above symbol.
    short_window - Lookback period for short moving average.
    long_window - Lookback period for long moving average."""

def __init__(self, symbol, bars, short_window=4, long_window=9):
    self.symbol = symbol
    self.bars = bars

    self.short_window = short_window
    self.long_window = long_window

    # Function Helper for indicators


def fill_for_noncomputable_vals(input_data, result_data):
    non_computable_values = np.repeat(
        np.nan, len(input_data) - len(result_data)
        )
    filled_result_data = np.append(non_computable_values, result_data)
    return filled_result_data

def simple_moving_average(data, period):
"""
Simple Moving Average.
Formula:
SUM(data / N)
"""
catch_errors.check_for_period_error(data, period)
# Mean of Empty Slice RuntimeWarning doesn't affect output so it is
# supressed
with warnings.catch_warnings():
    warnings.simplefilter("ignore", category=RuntimeWarning)
    sma = [np.mean(data[idx-(period-1):idx+1]) for idx in range(0, len(data))]
sma = fill_for_noncomputable_vals(data, sma)
return sma


def hull_moving_average(data, period):
    """
    Hull Moving Average.
    Formula:
    HMA = WMA(2*WMA(n/2) - WMA(n)), sqrt(n)
    """
    catch_errors.check_for_period_error(data, period)
    hma = wma(
        2 * wma(data, int(period/2)) - wma(data, period), int(np.sqrt(period))
        )
    return hma


def generate_signals(self):
    """Returns the DataFrame of symbols containing the signals
    to go long, short or hold (1, -1 or 0)."""
    signals = pd.DataFrame(index=self.bars.index)
    signals['signal'] = 0.0

    # Create the set of moving averages over the 
    # respective periods
    signals['Fast_Line'] = sma(bars['Close'], self.short_window)
    signals['Slow_line'] = hma(bars['Close'], self.long_window)
    signals1['Fast_Line'] = sma(bars['Close'], self.short_window[-1])
    signals1['Slow_line'] = hma(bars['Close'], self.long_window[-1])

    # Create a 'signal' (invested or not invested) when the short moving average crosses the long
    # moving average, but only for the period greater than the shortest moving average window
    signals['signal'][self.short_window:] = np.where(signals['Fast_Line'][self.short_window:] 
        > signals['Slow_line'][self.short_window:], 1.0, 0.0)   

    # Take the difference of the signals in order to generate actual trading orders
    signals['positions'] = signals['signal'].diff()   

    if signals['Fast_Line'] = signals['Slow_Line'] and ...
    return signals

希望我的问题有道理。

1 个答案:

答案 0 :(得分:0)

我假设你想在实时市场中使用它之前先测试你的策略。您可以以csv格式从yahoo finance下载股票数据。您可以使用以下代码上传:

import pandas as pd
import numpy as np
data = pd.read_csv('MSFT.csv')

一旦数据存储在pandas数据帧数据中,您可以使用以下代码移动平均价格: 如果你正在计划交叉策略

sma_days=20
lma_days=50

data['SMA_20']=data['Close'].rolling(window=sma_days,center=False).mean() data['SMA_50']=data['Close'].rolling(window=lma_days,center=False).mean() data['SIGNAL']=np.where(data['SMA_20']>data['SMA_50'],'BUY','SELL')