To jest mój program, który znajduje optymalne parametry p1 i p2 dla 2 funkcji. Danymi są ceny inwestycyjne - Low, High, Close. Program działa (można go uruchomić, dane załączam), ale wypisuje mi jeszce jakiś błąd, którego nie daję rady zinterpretować i podaje jakieś dodatkowe parametry p1 i p3. Czy może ktoś rzucić na to oko i jakoś z tym pomóc? Dziękuję.

**Błąd:
**

C:\Users\Beata\PycharmProject\1\venv\Scripts\python.exe C:/Users/Beata/PycharmProject/1/oscil(opt).py
C:\Users\Beata\PycharmProject\1\venv\lib\site-packages\pandas\core\indexing.py SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self._setitem_with_indexer(indexer, value)
p1: 1, p2: 1
p1: 1, p2: 5
p1: 1, p2: 9
C:/Users/Beata/PycharmProject/1/oscil(opt).py RuntimeWarning: invalid value encountered in double_scalars
return (np.sqrt(N) * returns.mean()) / (returns.std())

**
Oto program:**

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as dates

def oscil_k(data1, data2, data3, N):
    oscil_k = np.zeros(data1.shape[0])
    for i in range(N, data1.shape[0]):
        oscil_k[i] = 100 * ((data3[i]-data1[i-N+1:i+1].min())/(data2[i-N+1:i+1].max()-data1[i-N+1:i+1].min()))
    return oscil_k
#data=low, data2 = high, data3 = close

def oscil_d(data, N):
    cs = np.cumsum(np.insert(data, 0, 0))
    ma = (cs[N:] - cs[:-N]) / N
    return np.insert(ma, 0, np.repeat(0, N - 1))

def strategy_KD(df, price_column_name1, price_column_name2, price_column_name3, p1, p2, taxes):
    #data=low, data2 = high, data3 = close
    df['oscil_k'] = oscil_k(df[price_column_name1].values, df[price_column_name2].values, df[price_column_name3].values, p1)
    df['oscil_d'] = oscil_d(df['oscil_k'].values, p2)
    df['Sell Entry'] = ((df['oscil_k'] < df['oscil_d']) & (df['oscil_k'].shift(1) > df['oscil_d'].shift(1))) & (df['oscil_d'] > 80)
    df['Buy Entry'] = ((df['oscil_k'] > df['oscil_d']) & (df['oscil_k'].shift(1) < df['oscil_d'].shift(1))) & (df['oscil_d'] < 20)
    #Create empty "Position" column
    df['Position'] = np.nan
    #Set position to -1 for buy signals
    df.loc[df['Buy Entry'],'Position'] = 1
    #Set position to -1 for sell signals
    df.loc[df['Sell Entry'],'Position'] = -1
    #Set starting position to flat (i.e. 0)
    df['Position'].iloc[0] = 0
    # Forward fill the position column to show holding of positions through time
    df['Position'] = df['Position'].fillna(method='ffill')
    df['Taxes'] = df['Sell Entry'] * taxes + df['Buy Entry'] * taxes 
    df['Price_change'] = df['Close'].diff(1)
    df.iloc[0, df.columns.get_loc('Price_change')] = 0 #pirmai dienai 0
    df['Profit_of_position'] = df['Position'] * df['Price_change']
    df['Total_profit'] = df['Taxes'] + df['Profit_of_position']
    return df['Total_profit']

data_pd = pd.read_csv('GS.csv')
format = '%m/%d/%Y'
data_pd['Date'] = pd.to_datetime(data_pd['Date'], format=format)
data_pd = data_pd.set_index(data_pd['Date'])  
data_pd = data_pd.drop(columns=['Date'])

p1, p2 = 14, 3
df = data_pd.copy()
price_column_name1 = 'Low'
price_column_name2 = 'High'
price_column_name3 = 'Close'
taxes = -0.03

res = strategy_KD(df, price_column_name1, price_column_name2, price_column_name3, p1, p2, taxes)
#print(rez)

# sharpe ratio
def annualised_sharpe(returns, N=252):
    #Calculate the annualised Sharpe ratio of a returns stream
    #based on a number of trading periods, N. N defaults to 252,
    #which then assumes a stream of daily returns.
    #The function assumes that the returns are the excess of
    #those compared to a benchmark.
    return (np.sqrt(N) * returns.mean()) / (returns.std())


df = data_pd.copy()
price_column_name1 = 'Low'
price_column_name2 = 'High'
price_column_name3 = 'Close'
taxes = 0

df_opt = pd.DataFrame(columns=['p1', 'p2', 'sharpe_ratio', 'res'])
for p1 in range(1,20,4):
    for p2 in range(1,20,4):
            print('p1: {}, p2: {}'.format(p1,p2))
            if p1 != p2:
                res = strategy_KD(df, price_column_name1, price_column_name2, price_column_name3, p1, p2, taxes)
                sharpe_ratio = annualised_sharpe(res)
                df_opt = df_opt.append({'p1': p1, 'p2': p2, 'sharpe_ratio': sharpe_ratio, 'res': res.copy()}, ignore_index = True) 

idx_max = df_opt['sharpe_ratio'].idxmax()
print('The biggest sharpe ratio ({}) we get with the parameters p1: {}, p2: {}'.format(df_opt.loc[idx_max]['sharpe_ratio'],
                                                                                 df_opt.loc[idx_max]['p1'],
                                                                                 df_opt.loc[idx_max]['p2']))

fig = plt.figure(figsize=(15, 5))
fig.add_axes()
ax = fig.add_subplot(111)
a = strategy_KD(data_pd, 'Low', 'High', 'Close', 14, 3, -0.03)
cs1 = np.cumsum(a)
ax.plot(cs1)
ax.plot(df_opt.loc[idx_max]['res'].cumsum()) 
ax.legend(['not optimized','optimized'])
date_formatter = dates.DateFormatter('%m/%d/%Y')
ax.xaxis.set_major_formatter(date_formatter)
ax.xaxis.set_major_locator(dates.MonthLocator(interval=12))
plt.setp(ax.xaxis.get_majorticklabels(), rotation=90, fontsize=7)
ax.set(title='GS trading strategy', ylabel='Price', xlabel='Date')
fig.autofmt_xdate()
ax.autoscale_view()
ax.grid()
#plt.plot(df_opt.loc[0]['rez'].cumsum())
#plt.plot(df_opt.loc[24]['rez'].cumsum())
plt.show()