Add macd to technical analysis

This commit is contained in:
didier
2020-12-25 01:13:53 +00:00
parent 2b2a3b0369
commit 0229a7b46a
3 changed files with 77 additions and 4 deletions

View File

@@ -54,6 +54,7 @@ def print_help(s_ticker, s_start, b_is_market_open):
print("\nTechnical Analysis:")
print(" sma simple moving average")
print(" ema exponential moving average")
print(" macd moving average convergence/divergence")
print("\nPrediction:")
print(" ma")
@@ -83,10 +84,18 @@ def main():
s_start = ""
df_stock = pd.DataFrame()
# Set stock by default to speed up testing
s_ticker = "TSLA"
s_start = datetime.strptime("2020-06-04", "%Y-%m-%d")
ts = TimeSeries(key=cfg.API_KEY_ALPHAVANTAGE, output_format='pandas')
df_stock, d_stock_metadata = ts.get_daily(symbol=s_ticker, outputsize='full')
df_stock = df_stock[s_start:]
# Delete above in the future
main_parser = argparse.ArgumentParser(prog='stock_market_bot', add_help=False)
# Add list of arguments that the main parser accepts
main_parser.add_argument('cmd', choices=['quit', 'help', 'gainers' ,'view', 'load', 'clear', 'sma', 'ema', 'ratings'])
main_parser.add_argument('cmd', choices=['quit', 'help', 'gainers' ,'view', 'load', 'clear', 'sma', 'ema', 'macd', 'ratings'])
# Print first welcome message and help
print("\nWelcome to Didier's Stock Market Bot\n")
@@ -161,6 +170,11 @@ def main():
elif ns_known_args.cmd == 'ema':
smta.ema(l_args, s_ticker, df_stock)
continue
# ---------------------------------------------------- MACD ----------------------------------------------------
elif ns_known_args.cmd == 'macd':
smta.macd(l_args, s_ticker, df_stock)
continue
# --------------------------------------------------------------------------------------------------------------
# ------------------------------------------------ PREDICTION --------------------------------------------------

View File

@@ -41,14 +41,29 @@ def plot_view_stock(df, symbol):
# -----------------------------------------------------------------------------------------------------------------------
def plot_stock_ta(df_stock, s_stock, df_ta, s_ta):
def plot_stock_ta(df_stock, s_ticker, df_ta, s_ta):
plt.plot(df_stock.index, df_stock.values)
plt.plot(df_ta.index, df_ta.values)
plt.title(f"{s_ta} on {s_stock}")
plt.title(f"{s_ta} on {s_ticker}")
plt.xlim(df_stock.index[0], df_stock.index[-1])
plt.xlabel('Time')
plt.ylabel('Share Price ($)')
plt.legend([s_stock, s_ta])
plt.legend([s_ticker, s_ta])
plt.grid(b=True, which='major', color='#666666', linestyle='-')
plt.minorticks_on()
plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)
plt.show()
print("")
# -----------------------------------------------------------------------------------------------------------------------
def plot_ta(s_ticker, df_ta, s_ta):
plt.plot(df_ta.index, df_ta.values)
plt.title(f"{s_ta} on {s_ticker}")
plt.xlim(df_ta.index[0], df_ta.index[-1])
plt.xlabel('Time')
plt.ylabel('Share Price ($)')
plt.legend(df_ta.columns)
plt.grid(b=True, which='major', color='#666666', linestyle='-')
plt.minorticks_on()
plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)

View File

@@ -63,3 +63,47 @@ def ema(l_args, s_ticker, df_stock):
except:
print("")
return
# ----------------------------------------------------- MACD -----------------------------------------------------
def macd(l_args, s_ticker, df_stock):
parser = argparse.ArgumentParser(prog='macd',
description=""" The Moving Average Convergence Divergence (MACD) is the difference
between two Exponential Moving Averages. The Signal line is an Exponential Moving
Average of the MACD. \n \n The MACD signals trend changes and indicates the start
of new trend direction. High values indicate overbought conditions, low values
indicate oversold conditions. Divergence with the price indicates an end to the
current trend, especially if the MACD is at extreme high or low values. When the MACD
line crosses above the signal line a buy signal is generated. When the MACD crosses
below the signal line a sell signal is generated. To confirm the signal, the MACD
should be above zero for a buy, and below zero for a sell. """)
parser.add_argument('-f', "--fast", action="store", dest="n_fast", type=check_positive, default=12,
help='The short period.')
parser.add_argument('-s', "--slow", action="store", dest="n_slow", type=check_positive, default=26,
help='The long period.')
parser.add_argument("--signal", action="store", dest="n_signal", type=check_positive, default=9,
help='The signal period.')
parser.add_argument('-o', "--offset", action="store", dest="n_offset", type=check_positive, default=9,
help='How many periods to offset the result.')
try:
(ns_parser, l_unknown_args) = parser.parse_known_args(l_args)
except SystemExit:
print("")
return
if l_unknown_args:
print(f"The following args couldn't be interpreted: {l_unknown_args}")
try:
df_ta = ta.macd(df_stock['4. close'],
fast=ns_parser.n_fast,
slow=ns_parser.n_slow,
signal=ns_parser.n_signal,
offset=ns_parser.n_offset).dropna()
plot_ta(s_ticker, df_ta, f"{ns_parser.n_fast}-{ns_parser.n_slow}-{ns_parser.n_signal}-{ns_parser.n_offset} MACD")
except:
print("")
return