Python Forum

Full Version: Moving average strategy
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use ('fivethirtyeight')`

import yfinance as yf

# Set the start and end date and cash
start_date = '2010-01-01'
end_date = '2020-01-01'

# Set the ticker
ticker = 'SPY'

# Get the data
df = yf.download(ticker, start_date, end_date)

def SMA10(data, period=10, column='Close'):
    return data [column].rolling(window=period).mean()
def SMA30(data, period=30, column='Close'):
    return data [column].rolling(window=period).mean()
# Set strategie
def strategy(df):
    buy = []
    sell = []
    flag = 0
    buy_price = 0

    for i in range(0, len(df)):

        if df['SMA10'] [i] > df['SMA30'] [i] and flag == 0:
            buy.append(df['Close'][i])
            sell.append(np.nan)
            buy_price = df['Close'][i]
            flag = 1
        elif df['SMA10'] [i] < df['SMA30'] [i] and flag == 1:
            sell.append(df['Close'][i])
            buy.append(np.nan)
            buy_price = 0
            flag = 0
        else:
            sell.append(np.nan)
            buy.append(np.nan)

    return (buy, sell)
Hi, can you help me to testing my strategy, for example: add a cash = 10.000, portfolio, and quantity of Stocks ( Order Size=quantity=(10000/df(Adj.Close)(i)
Thanks a lot.
Hi irina_shubina.

See the following Python code.


import numpy as np
import pandas as pd
import yfinance as yf
import matplotlib.pyplot as plt

plt.style.use ('fivethirtyeight')


start_date = '2010-01-01' # start and end date
end_date = '2020-01-01'
ticker = 'SPY' # Set the ticker
cash=10_000 # cash
df=yf.download(ticker,start_date, end_date)
nShare=int(cash/df['Close'][1])
n=np.shape(df)[0]
totalRet=(1+df['Adj Close'].pct_change()).prod()-1
totalRet # Out[836]: 2.468748704035219
totalValue=cash*(1+totalRet)
totalValue # 34687.50232472107 # benchmark


def SMA(data, period=10):
return data['Close'].rolling(window=period).mean()

df['SMA10']=SMA(df)
df['SMA30']=SMA(df,30)

# Set strategie
buy = []
sell = []
long=0 # flag = 0
dd=[]
flag2=[]
aa=[]
bb=[]
for i in range(0, len(df)): #for i in range(31, len(df)):
a=df['SMA10'][i]
b=df['SMA30'][i]
aa.append(a)
bb.append(b)
dd.append(df.index[i])
if(a!=np.NaN and b!=np.NaN):
if a > b and long == 0:
buy.append(df['Close'][i])
sell.append(np.nan)
long=1 # flag = 1
elif a < b and long == 1:
sell.append(df['Close'][i])
buy.append(np.nan)
long=0 # flag = 0 # sell thus postion is zero
else:
sell.append(np.nan)
buy.append(np.nan)
p=1 # place holder
flag2.append(long)

#
final=pd.DataFrame([buy,sell,flag2,aa,bb]).T
final.index=dd
final.columns=['buyPrice','sellPrice','long','SMA10','SMA30']
#final.to_csv("strategy.csv")
ret2=df['Adj Close'].pct_change()*final['long']
totalRet2=(1+ret2).prod()-1
totalValue2=cash*(1+totalRet2)
totalValue2 # Out[834]: 23747.6188958821
totalRet2 # Out[832]: 1.37476188958821

[python][python]
[/python][/python]
import numpy as np
import pandas as pd
import yfinance as yf
import matplotlib.pyplot as plt

plt.style.use ('fivethirtyeight')
 

start_date = '2010-01-01'   # start and end date 
end_date = '2020-01-01'    
ticker = 'SPY'              # Set the ticker
cash=10_000                 # cash 
df=yf.download(ticker,start_date, end_date)
nShare=int(cash/df['Close'][1])
n=np.shape(df)[0]
totalRet=(1+df['Adj Close'].pct_change()).prod()-1
totalRet  # Out[836]: 2.468748704035219
totalValue=cash*(1+totalRet)
totalValue  # 34687.50232472107      # benchmark


def SMA(data, period=10):
    return data['Close'].rolling(window=period).mean()

df['SMA10']=SMA(df)
df['SMA30']=SMA(df,30)   

# Set strategie
buy = []
sell = []
long=0 # flag = 0
dd=[]
flag2=[]
aa=[]
bb=[]
for i in range(0, len(df)):   #for i in range(31, len(df)):
    a=df['SMA10'][i]
    b=df['SMA30'][i]
    aa.append(a)
    bb.append(b)
    dd.append(df.index[i])
    if(a!=np.NaN and b!=np.NaN):
        if a > b and long == 0:
            buy.append(df['Close'][i])
            sell.append(np.nan)
            long=1  # flag = 1       
        elif a < b and long == 1:
            sell.append(df['Close'][i])
            buy.append(np.nan)
            long=0 #  flag = 0                 # sell thus postion is zero
        else:
            sell.append(np.nan)
            buy.append(np.nan)
            p=1   # place holder
    flag2.append(long)        
    
#
final=pd.DataFrame([buy,sell,flag2,aa,bb]).T
final.index=dd    
final.columns=['buyPrice','sellPrice','long','SMA10','SMA30']
#final.to_csv("strategy.csv")
ret2=df['Adj Close'].pct_change()*final['long']
totalRet2=(1+ret2).prod()-1
totalValue2=cash*(1+totalRet2)
totalValue2   # Out[834]: 23747.6188958821
totalRet2     # Out[832]: 1.37476188958821