<jupyter_start><jupyter_text>Pivot Points tradingWe would try pivot points trading. The following formulas would be used * P = (H+L+C)/3 * R1 = 2 * P - L * S1 = 2 * P - H * R2 = P + (H - L) * S2 = P - (H - L) * R3 = R1 + (H- L) * S3 = S1 - (H - L)<jupyter_code># Import the necessary libraries
import pandas as pd
import seaborn as sns
sns.set()
from fastbt.datasource import DataSource
from fastbt.rapid import *
# Loading data
df = pd.read_csv('data/data.csv', parse_dates=['timestamp'])
# Let's look at the first 5 rows
df.head()<jupyter_output><empty_output><jupyter_text>Let's add all the formulas above.I use the eval function to use the formula directly. The `eval` function is used to evaluate expression as formulas. So instead of writing```python    df['p'] = (df['high'] + df['low'] + df['close'])/3```you could used```python    df['p'] = df.eval('(high+low+close)/3')```<jupyter_code># Now add the necessary formulas

df['_p'] = df.eval('(high+low+close)/3')
df['_r1'] = df.eval('2*_p-low')
df['_s1'] = df.eval('2*_p-high')
df['_r2'] = df.eval('_p+(high-low)')
df['_s2'] = df.eval('_p-(high-low)')
df['_r3'] = df.eval('_r1+(high-low)')
df['_s3'] = df.eval('_s1-(high-low)')<jupyter_output><empty_output><jupyter_text>The pivot points we calculated are based on the data for the end of the data. We need this data for the next day to make trades. So, I would just be lagging the data for these columns for one day.*The columns would now be named without underscore.*<jupyter_code>cols = ['_p', '_r1', '_r2', '_r3', '_s1', '_s2', '_s3']
ds = DataSource(df)
for col in cols:
    ds.add_lag(on=col, period=1, col_name=col[1:])

# Let's add the daily return 
ds.add_formula('(prevclose/close)-1', col_name='ret')
ds.add_lag(on='ret', period=1, col_name='retprev');<jupyter_output><empty_output><jupyter_text>Let's take a look at the correlation to see whether these points have any effect. Looks nothing interesting<jupyter_code>ds.data.corr()['ret'].sort_values()<jupyter_output><empty_output><jupyter_text>Let's create the parameters for backtestWe would place buy orders when the price hits the first support and hold till the end of the day. We would select 3 orders every day sorted according to price (this is *dumb* but we need some security selection)<jupyter_code># Backtest parameters
# 

params = {
    'data': ds.data.dropna(),
    'limit': 3,
    'sort_by': 'price',
    'order': 'B',
    'price': 's1-0.05', # Buy only when price falls below support
    'stop_loss': 100, # No stop loss,
    'commission': 0.05
}
results = backtest(**params)
results.groupby('timestamp').profit.sum().cumsum().plot(
    title='Cumulative Profit')<jupyter_output><empty_output><jupyter_text>Let's try selling orders at first resistance and holding them till the end of the day<jupyter_code>params = {
    'data': ds.data.dropna(),
    'limit': 3,
    'sort_by': 'price',
    'order': 'S',
    'price': 'r1+0.05', # Buy only when price goes above resistance
    'stop_loss': 100, # No stop loss,
    'commission': 0.05
}

results2 = backtest(**params)
results2.groupby('timestamp').profit.sum().cumsum().plot(
    title='Cumulative Profit')<jupyter_output><empty_output><jupyter_text>Wow, we got profit in both these cases.Let's try out a different sort mode, on previous day return<jupyter_code>params.update({'sort_by': 'retprev'})
backtest(**params).groupby('timestamp').profit.sum().cumsum().plot(
    title='Cumulative Profit')<jupyter_output><empty_output><jupyter_text>We see no big difference in results.Let's merge the results and see the trades.<jupyter_code>final = pd.concat([results, results2], sort=False).reset_index(drop=True)

# Delete unwanted columns
for col in final.columns:
    if col.startswith('_'):
        del final[col]

pd.options.display.max_columns = 50
final.sort_values(by='timestamp').set_index('timestamp').head()<jupyter_output><empty_output><jupyter_text>Is this really profitable?Let's check out the metrics<jupyter_code>metrics(final, capital=20000)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.15227668574272207, 'fraction_numerical': 0.016919631749191342, 'mean_word_length': 5.232558139534884, 'pattern_counts': {'":': 0, '<': 37, '<?xml version=': 0, '>': 37, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '318678', 'license': 'MIT', 'n_tokens_mistral': 1447, 'n_tokens_neox': 1385, 'n_words': 397, 'path': 'examples/PivotPoints.ipynb', 'repo_name': 'webclinic017/fastbt', 'size': '4019'}