Created
November 18, 2020 22:14
-
-
Save rm-rf-etc/6fc50dc8ec562bef815a2231888a4c7d to your computer and use it in GitHub Desktop.
HA Candles Backtest
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
import yfinance as yf | |
import pandas as pd | |
import numpy as np | |
import pandas_datareader as pdr | |
import matplotlib.pyplot as plt | |
import plotly | |
import plotly.graph_objects as go | |
yf.pdr_override() | |
stock = yf.Ticker("SPY") | |
df = stock.history(period="10y", interval="1d") | |
df['OpenS'] = df['Open'].shift(1) | |
df['CloseS'] = df['Close'].shift(1) | |
nums = [0] | |
for i in range(len(df)): | |
number = nums[-1] + 1 | |
nums.append(number) | |
df['rownum'] = nums[1:] | |
df['returns'] = df['Close'].pct_change() | |
df['returnsS'] = df['returns'].shift(-1) | |
df['HA Close'] = (df['Open'] + df['Close'] + df['Low'] + df['Close']) * .25 | |
df['HA Open'] = (df['OpenS'] + df['CloseS']) * .5 | |
df['HA Low'] = df['Low'] | |
df['HA High'] = df['High'] | |
df['position'] = np.where(df['HA Close'] > df['HA Open'] , 1 , 0) | |
df['strat returns'] = np.where(df['position'] ==1 , 1 + df['returnsS'] , 1) | |
df['adj close'] = df['Close'] / df['Close'][0] | |
df['cumreturns'] = df['strat returns'].cumprod() | |
df['cumreturns'].plot(figsize = (21,9)) | |
df['adj close'].plot() | |
plt.legend(); |
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
fig = go.Figure(data=[go.Candlestick(x=df['rownum'], | |
open=df['HA Open'], | |
high=df['HA High'], | |
low=df['HA Low'], | |
close=df['HA Close'])]) | |
fig.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment