简体   繁体   中英

Python script for algo trading using

Looking for suggestions for Python program for trading Forex. Basically I want to use short sma and long sma crosses to trigger buy long or short, but only just after it crosses not when it is already above to go long or below to go short. The second part is to use a short sma crossing a medium sma to exit the position. The problem I am running into is the short and medium sma's keep triggering buy and sells, when they are above or below the long sma. I do not want to enter any trades using the sma short and medium crosses only to exit positions, that I have entered previously on the short/long sma cross.

This script seems to be getting close to what I am looking for. It has the short/long signal when exact time they cross. It does not have the sma short and medium cross to exit a position and no failsafe so it does not trigger any buys or sells to enter a trade when they cross otherwise. I only want the short/medium cross to exit trades, after I enter on the long/short sma cross.

df['position'] = df['SMA_15'] > df['SMA_45']
df['pre_position'] = df['position'].shift(1)
df.dropna(inplace=True) # dropping the NaN values
df['crossover'] = np.where(df['position'] == df['pre_position'], False, True)

I could show you a solution that only grabs the first buy signal from each little string of buys and sells repeated, but I believe you might like a library called tulipy . This allows you to easily make technical indicators (For more functions, here's the docs https://tulipindicators.org/ ). If you want that other solution, feel free to comment that and I'll add it here.

pip install tulipy To install the library

Utilize the crossover function. We also have to keep the lists the same length here.

import pandas as pd
import numpy as np
import tulipy

def makeListsSameLength(someList, matchThisLengthList):
    #make someList the same length as matchThisLengthList by adding None's to the front
    for i in range(abs(len(matchThisLengthList) - len(someList))): 
        someList = np.insert(someList, 0, None, axis=0) #Push a None to the front of the list
    return someList

df['SMA_15'] = makeListsSameLength(tulipy.sma(df['close'].values, 15), df)
df['SMA_45'] = makeListsSameLength(tulipy.sma(df['close'].values, 45), df)
df['crossover'] = makeListsSameLength(tulipy.crossover(df['SMA_15'].values, df['SMA_45'].values), df)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM