def add(a, b):
return a + b
add(1, 2)
from talib import abstract
from datetime import datetime
import backtrader as bt
def fibo(self):
# calculate the fibonacci levels
# find the maxima and minima
# get the index of the extreme candle
# plot the fibonacci levels from 0 to 1 on the extreme candle
fibo()
def Fibo(a, b):
return a + b
Fibo(1, 2)
def fibo(t):
n = len(t)
return [t[int(n) * i] for i in fibonacci_sequence(1)][1:]
#detect max and min
max_in_range = max(df['High'].iloc[int(start):int(end)])
min_in_range = min(df['Low'].iloc[int(start):int(end)])
#determine max and min indices
max_index = df[df['High'] == max_in_range].index[0]
min_index = df[df['Low'] == min_in_range].index[0]
#plot fibo
start, end = max_index, min_index
trace(df['Close'].iloc[int(start):int(end)], fibo(df['Close'].iloc[int(start):int(end)]))
def find_extremes(data):
max_candle = data.iloc[0]
min_candle = data.iloc[0]
for i, row in data.iterrows():
if row['high'] > max_candle['high']:
max_candle = row
if row['low'] < min_candle['low']:
min_candle = row
max_candle_index = data.index.get_loc(max_candle.name)
min_candle_index = data.index.get_loc(min_candle.name)
max_extremes = data.iloc[max_candle_index - 5:max_candle_index+5]
min_extremes = data.iloc[min_candle_index - 5:min_candle_index+5]
max_prices = max_extremes['high'].tolist()
min_prices = min_extremes['low'].
def search_fibo(symbol, timeframe, max_candles, min_candles):
# 1. Find MAX and MIN from the chart.
chart = fetch_ohlcv(symbol, timeframe)
chart_max = chart.iloc[-max_candles:].max()
chart_min = chart.iloc[-min_candles:].min()
# 2. Determine the candle of the extremum and build Fibonacci levels
if chart_max == chart['high'].max():
extreme_candle = chart[chart['high'] == chart_max]
build_fibo(symbol, timeframe, extreme_candle.index[0])
elif chart_min == chart['low'].min():
extreme_candle = chart[chart['low'] == chart_min]
build_fibo(symbol, timeframe, extreme_candle.index[0])
import plotly.graph_objs as go
from plotly.offline import plot
import talib
import plotly
def fibonacci_levels(df):
a = df.Close.values
b = df.High.values
c = df.Low.values
x = talib.MAX(b, timeperiod=1)
y = talib.MIN(c, timeperiod=1)
z = x-y
o = y.tolist()
p = o.index(x[-1])
q = df.Date.iloc[p]
r = df.Date.iloc[-1]
d = df.Date.tolist()
e = d.index(q)
f = d.index(r)
fig = go.Figure()
fig.add_trace(go.Scatter(x=df.Date[e:f], y=df.Close[e:f], mode="lines", name="BNBUSDT"))
fig.add_trace(go.Scatter
def fibonacci(data):
min = data[data['low'] == min(data['low'])]
max = data[data['high'] == max(data['high'])]
# fibonacci
fib = [0, 0.236, 0.382, 0.5, 0.618, 0.786, 1]
for i in fib:
plt.axhline(min['low'].values[0] + ((max['high'].values[0] - min['low'].values[0]) * i), linestyle='--', c='r')
plt.plot(data['close'])
plt.show()
def draw_Fibonacci_line(df, interval, candlestick_interval):
df['H-L'] = df['High'] - df['Low']
df['H-PC'] = abs(df['High'] - df['Adj Close'].shift(1))
df['L-PC'] = abs(df['Low'] - df['Adj Close'].shift(1))
df['TR'] = df[['H-L', 'H-PC', 'L-PC']].max(axis=1)
df['ATR'] = df['TR'].rolling(interval).mean()
df['Fibb_0'] = 0
df['Fibb_0.236'] = df['ATR']*0.236
df['Fibb_0.382'] = df['ATR']*0.382
df['Fibb_0.5'] = df['ATR']*0.5
df['Fibb_0.618'] = df['ATR']*0.618
df['F
def fibonacci_levels(df):
# Find the maximum and minimum of candles that have an extreme position
maximum = df.iloc[df.High.idxmax()].High
minimum = df.iloc[df.Low.idxmin()].Low
# Use the function to find the Fibonacci levels
fibonacci = fib_retracements(df['High'], df['Low'])
# Draw the Fibonacci levels on the chart
plt.figure(figsize=(10,5))
plt.plot(df.index, df.High, label = 'High')
plt.plot(df.index, df.Low, label = 'Low')
plt.plot(df.index, df.Close, label = 'Close')
plt.plot(df.index, df.Open, label = 'Open')
plt.axhline(y=maximum, color='blue', linestyle='-')
plt.axhline(y=minimum, color='red', linestyle='
def fibonacci(chart, candle, num_lines, param):
# chart: chart object
# candle: number of the candle to draw fibo from
# num_lines: number of lines to draw
# param: either 'max' or 'min' to determine from candle low or high to draw fibo from
# set baseline and extreme
baseline = getattr(chart.iloc[candle], param)
extreme = getattr(chart.iloc[candle], param)
# set baseline to candle before
baseline = getattr(chart.iloc[candle-1], param)
# find the next candle with a higher high
for i in range(candle+1, len(chart)):
if getattr(chart.iloc[i], param) > extreme:
extreme = getattr(chart.iloc[i], param)
else:
break
# find the next candle with a lower low
for i in range(candle+1, len(chart)):
if
def find_extremes(dataframe):
high = dataframe['high'].max()
low = dataframe['low'].min()
extreme_candle = dataframe[dataframe['high'] == high]
extreme_candle = extreme_candle[extreme_candle['low'] == low]
if len(extreme_candle) != 1:
raise Exception('More than one candle is extreme')
extreme_price = extreme_candle['close'].values[0]
fibs = [0.0, 0.382, 0.5, 0.618, 1.0]
fib_prices = [extreme_price * (1 - x) + x * low for x in fibs]
return fib_prices
# Function to search for the most recent minimum and maximum
# Add function for min and max
def find_min_max(data):
min_value = data[0]['close']
max_value = min_value
min_index = 0
max_index = 0
for i in range(1, len(data)):
if data[i]['close'] < min_value:
min_value = data[i]['close']
min_index = i
if data[i]['close'] > max_value:
max_value = data[i]['close']
max_index = i
return min_index, max_index
min_index, max_index = find_min_max(data)
# Function to calculate the Fibonacci levels
# Add function for fibonacci levels
def fib_retracement(data, index, levels=[0, 0.07, 0.15, 0.23, 0.38, 0.50, 0.61, 0.78, 1.0]):
def fibonacci_retracements(chart, days):
high = chart.iloc[-1]['high']
low = chart.iloc[-1]['low']
if days > 5:
high = chart.iloc[-days:-1]['high'].max()
low = chart.iloc[-days:-1]['low'].min()
print(high, low)
fibs = []
for i in range(0,11):
fibs.append(low + (high-low)*i/10)
return fibs
fibs = fibonacci_retracements(chart, 10)
fibs
def search_max_min(df, long_num_candles, short_num_candles, step_candles):
df = df.reset_index(drop=True)
for i in range(0, len(df), step_candles):
print(i)
if i > long_num_candles + short_num_candles + 1:
sub_df = df.loc[i-long_num_candles-short_num_candles:i, ["high", "low"]]
max_price = sub_df["high"].max()
min_price = sub_df["low"].min()
if df.loc[i-short_num_candles, "close"] == max_price:
print("max")
df.loc[i-short_num_candles, "max_min"] = "max"
elif df.loc[i-short_num_candles, "close"] == min_price:
print("min")
df.loc[i-short_num_
import plotly.graph_objects as go
def plotFib(df, minimum, maximum):
fig = go.Figure()
fig.add_trace(go.Scatter(
x=df['time'],
y=df['close'],
mode='lines',
line=dict(color='rgb(0,0,0)')
))
fig.add_trace(go.Scatter(
x=[minimum['time'], minimum['time']],
y=[minimum['close'],maximum['close']],
mode='lines',
line=dict(color='rgb(0,0,0)', width=2)
))
fig.add_trace(go.Scatter(
x=[maximum['time'], maximum['time']],
y=[minimum['close'],maximum['close']],
mode='lines',
fill='tozeroy',
fillcolor='rgba(255, 0, 0, 0.2)',
line=dict(color='rgba(255, 0,
### Testing
* When you run `python3 -m unittest`, all python files in the current directory that start with `test_` will be run.
* If you wish to run a specific test, you can use `python3 -m unittest test_example.py`.
* You can also use `python3 -m unittest test_example.TestAdd` to run a specific test case.
* You can run tests from a single file by using the `-f` flag: `python3 -m unittest -f`
* You can also use the `-c` flag to exclude certain tests.
* You can run tests with a specific argument by using the `-a` flag: `python3 -m unittest -a <argument>`
* You can also run tests with a custom argument by using the `-c` flag: `python3 -m unittest -c <custom_argument>`
*
### Writing tests
* In order to write tests, we need to understand the basic structure of a test.