-
-
Save anthonymorast/e0ad70f876a0c6ad41f85b301debd5e9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if __name__ == '__main__': | |
# the subdirectory for my project you may need to change this | |
base_dir = "./BollingerBot/" | |
img_dir = base_dir + "imgs/" | |
tickers = pd.read_csv(base_dir + "sp500tickers.csv")["symbol"].tolist() | |
end_dt = datetime.datetime.today() | |
start_dt = datetime.datetime(end_dt.year - 1, end_dt.month, end_dt.day) | |
api = YahooFinanceAPI(Interval.DAILY) | |
progress_count = 1 | |
results_dict = { | |
"ticker": [], | |
"profit": [], | |
"avg_return": [], | |
"start_price": [] | |
} | |
for ticker in tickers: | |
print("Processing ticker symbol {} ({} out of {}).".format(ticker.upper(), progress_count, len(tickers))) | |
try: | |
# fetch the data | |
data = api.get_ticker_data(ticker, start_dt, end_dt) | |
except: | |
# don't care if we can't | |
progress_count += 1 | |
continue | |
data['ma'] = get_sma(data["Close"], 20) # get 20-period SMA | |
data['upper'], data['lower'] = get_bollinger_bands(data['Close'], data['ma'], 20) | |
# plot the bands + close price | |
data['Close'][20:].plot(label='close', color='darkcyan') | |
data['ma'].plot(label='mid', linestyle='--', linewidth='0.9', color='darkturquoise') | |
data['upper'].plot(label='upper', linestyle='--', linewidth='1.1', color='indianred') | |
data['lower'].plot(label='lower', linestyle='--', linewidth='1.1', color='lightgreen') | |
# determine trades, calculate profit, and store results | |
trades = get_buy_sell_points(data) | |
avg_return, profit = calculate_profits(trades, ticker, base_dir) | |
results_dict["ticker"].append(ticker.upper()) | |
results_dict["profit"].append(profit) | |
results_dict["avg_return"].append(avg_return) | |
results_dict["start_price"].append(data.loc[0]["Close"]) | |
print("Average return per trade: {}\t\tTotal profit trading one share: {}".format(avg_return, profit)) | |
# plot the trades and make the graph prettier | |
plt.scatter(trades["buy_indices"], trades["buy_prices"], marker="^", color="darkgreen", s=100, label="buy") | |
plt.scatter(trades["sell_indices"], trades["sell_prices"], marker="v", color="darkred", s=100, label="sell") | |
plt.title("Bollinger Bands w/ Trades for {}".format(ticker.upper())) | |
plt.legend(loc='upper left') | |
plt.savefig(img_dir + "{}_plot.png".format(ticker.upper())) | |
#plt.show() | |
plt.clf() | |
progress_count += 1 | |
# export the results to CSV | |
results_df = pd.DataFrame.from_dict(results_dict) | |
results_df.to_csv(base_dir + "results.dat", index=False) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment