Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Moving average strategy
#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


Messages In This Thread
Moving average strategy - by irina_shubina - Nov-26-2021, 03:48 PM
RE: Moving average strategy - by paulyan - Jul-31-2022, 05:02 PM
RE: Moving average strategy - by paulyan - Jul-31-2022, 05:11 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  strategy to troubleshoot what pyinstaller misses hammer 0 973 May-23-2022, 01:05 AM
Last Post: hammer
  Best strategy for creating .exe for windows hammer 4 1,548 Apr-05-2022, 12:47 AM
Last Post: hammer
  Strategy on updating edits back to data table and object variables hammer 0 1,221 Dec-11-2021, 02:58 PM
Last Post: hammer
  calculate daily return in percent in forex as to some strategy? alen 1 2,241 Mar-12-2021, 10:03 AM
Last Post: buran
  Python learning strategy IluvPython 6 3,306 Nov-04-2019, 07:41 PM
Last Post: buran
  What is the strategy for working with class variables? AlekseyPython 3 3,059 Feb-24-2019, 05:34 AM
Last Post: AlekseyPython
  Python and strategy pattern tanc 5 3,456 Nov-30-2018, 08:55 AM
Last Post: Gribouillis
  best parallelisation strategy on python simona 1 2,255 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