Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Moving average strategy
#1
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.
Larz60+ write Nov-26-2021, 06:22 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed for you this time. Please use bbcode tags on future posts.
Reply
#2
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]
Reply
#3
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  strategy to troubleshoot what pyinstaller misses hammer 0 912 May-23-2022, 01:05 AM
Last Post: hammer
  Best strategy for creating .exe for windows hammer 4 1,453 Apr-05-2022, 12:47 AM
Last Post: hammer
  Strategy on updating edits back to data table and object variables hammer 0 1,163 Dec-11-2021, 02:58 PM
Last Post: hammer
  calculate daily return in percent in forex as to some strategy? alen 1 2,181 Mar-12-2021, 10:03 AM
Last Post: buran
  Python learning strategy IluvPython 6 3,166 Nov-04-2019, 07:41 PM
Last Post: buran
  What is the strategy for working with class variables? AlekseyPython 3 2,947 Feb-24-2019, 05:34 AM
Last Post: AlekseyPython
  Python and strategy pattern tanc 5 3,330 Nov-30-2018, 08:55 AM
Last Post: Gribouillis
  best parallelisation strategy on python simona 1 2,178 Apr-19-2018, 01:51 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020