This notebook demonstrates the use of my financial calculations library to determine how a stategy will perform. Assuming that historical data is fairly representative of future data.
import numpy as np
import pandas as pd
import pandas_datareader as pdr
import matplotlib.pyplot as plt
%matplotlib inline
import sys
sys.path.insert(0,'./financial_calcs/')
import trading_calcs.standard as std_calcs
from datetime import timedelta
import datetime
date1 = datetime.date.today()
date_earlier = date1+timedelta(days=-60)
date_90_days_ago = date1+timedelta(days=-90)
date_90_days_ago_iso = date_90_days_ago.isoformat()
last_60_days_iso = date_earlier.isoformat()
stock_symbol = 'FSM'
df1 = pdr.get_data_yahoo([stock_symbol],start=last_60_days_iso)
df1.tail()
df1 = round(df1,4)
df1.head(7)
settings_file = "./financial_calcs/optimal_settings_file.json"
st1 = std_calcs.Strategy(stock_symbol, df1, settings_file)
st1
Get the settings from the settings file, this stores the parameters from the previous run.
st1.get_settings()
Uncomment the following to optimize the strategy based on the most current data, and also to update the settings file. The optimize_strategy() method runs the back-testing to see which strategy has the best returns.
#st1.optimize_strategy()
#st1.update_settings_file()
Various calculations based on the current strategy.
st1.calculate_strategy()
The best settings gives you a percent return, overbought and oversold and stops.
st1.best_settings
stops_periods = int(st1.best_settings['stops_periods'])
stops_mult = int(st1.best_settings['stops_mult'])
rsi_periods = int(st1.best_settings['rsi_periods'])
rsi_high = int(st1.best_settings['rsi_high'])
rsi_low = int(st1.best_settings['rsi_low'])
std_calcs.calc_range_position(df1['Close'][stock_symbol].iloc[-1].item(),df1['Low'][stock_symbol].iloc[-1].item(),st1.df_stops, st1.s_rsi, rsi_high, rsi_low)
The following shows a chart with the strategy positions. 1 is buy, 0 is hold, and -1 is sell.
df2 = pd.concat([st1.data_frame['Close'][st1.stock_symbol], st1.df_stops, st1.s_pos], axis=1)
df2.plot(figsize=(12, 9), secondary_y='Position')