Algo code assistaance

Hi,

Can anybody help me with the below code. I am trying to execute this code in Ibridgepy, but it is not working.

The objective is to load the historical data, calculate moving averages, bollinger bands, donchian channel

After this, I want to look to create an algo based on last 15 periods of above values



Also, any suggestions on improvement would be more than welcome.



The code is below:



import pandas as pd

import numpy as np



def initialize(context):

    context.security = superSymbol(secType='FUT', symbol='USDINR', currency='INR', exchange='NSE', expiry='20200626', multiplier='1000', includeExpired=True, localSymbol='USDINR20JUNFUT')

    



def handle_data(context, data):

    # Method 1: IBridgePy function request_historical_data(str_security, barSize, goBack)

    # Users have more controls on this function.

    # http://www.ibridgepy.com/ibridgepy-documentation/#request_historical_data

    print ('Historical Data of %s' % (str(context.security, ),))

    df = request_historical_data(context.security, '1 min', '5 D')

    print(df)

    print(df.iloc[-1]['close'])



    for sma_period in [5,10,20,50,100,200]:

        indicator_name = "SMA_%d" % (sma_period)

        df[indicator_name] = df['Close'].rolling(sma_period).mean()



df['BollingerBand_Up_20_2'] = df['Close'].rolling(20).mean() + 2df['Close'].rolling(20).std()

df['BollingerBand_Down_20_2'] = df['Close'].rolling(20).mean() - 2
df['Close'].rolling(20).std()

df['BollingerBand_Up_20_1'] = df['Close'].rolling(20).mean() + df['Close'].rolling(20).std()

df['BollingerBand_Down_20_1'] = df['Close'].rolling(20).mean() - df['Close'].rolling(20).std()

df['BollingerBand_Up_10_1'] = df['Close'].rolling(10).mean() + df['Close'].rolling(10).std()

df['BollingerBand_Down_10_1'] = df['Close'].rolling(10).mean() - df['Close'].rolling(10).std()

df['BollingerBand_Up_10_2'] = df['Close'].rolling(10).mean() + 2df['Close'].rolling(10).std()

df['BollingerBand_Down_10_2'] = df['Close'].rolling(10).mean() - 2
df['Close'].rolling(10).std()



for channel_period in [5,10,20,50,100,200]:

    up_name = "Donchian_Channel_Up_%d" % (channel_period)

    down_name = "Donchian_Channel_Down_%d" % (channel_period)

    

    df[up_name] = df['High'].rolling(channel_period).max()

    df[down_name] = df['Low'].rolling(channel_period).min()



#create 15 period lag

for lag in [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]:

    shift = lag

    shifted = df.shift(shift)

    shifted.columns = [str.format("%s_shifted_by_%d" % (column ,shift)) for column in shifted.columns]

    print(df)

    print(df.iloc[-1]['close'])

    end().

Hello Ashish,



The code isn't indented properly. 



Try this: 



---------------------------------------------------------------------------------------



def initialize(context):

    context.security = superSymbol(secType='FUT', symbol='USDINR', currency='INR', exchange='NSE', expiry='20200626', multiplier='1000', includeExpired=True, localSymbol='USDINR20JUNFUT')

    



def handle_data(context, data):

    # Method 1: IBridgePy function request_historical_data(str_security, barSize, goBack)

    # Users have more controls on this function.

    # http://www.ibridgepy.com/ibridgepy-documentation/#request_historical_data

    print ('Historical Data of %s' % (str(context.security, ),))

    df = request_historical_data(context.security, '1 min', '5 D')

    print(df)

    print(df.iloc[-1]['close'])



    for sma_period in [5,10,20,50,100,200]:

        indicator_name = "SMA_%d" % (sma_period)

        df[indicator_name] = df['Close'].rolling(sma_period).mean()



    df['BollingerBand_Up_20_2'] = df['Close'].rolling(20).mean() + 2df['Close'].rolling(20).std()

    df['BollingerBand_Down_20_2'] = df['Close'].rolling(20).mean() - 2
df['Close'].rolling(20).std()

    df['BollingerBand_Up_20_1'] = df['Close'].rolling(20).mean() + df['Close'].rolling(20).std()

    df['BollingerBand_Down_20_1'] = df['Close'].rolling(20).mean() - df['Close'].rolling(20).std()

    df['BollingerBand_Up_10_1'] = df['Close'].rolling(10).mean() + df['Close'].rolling(10).std()

    df['BollingerBand_Down_10_1'] = df['Close'].rolling(10).mean() - df['Close'].rolling(10).std()

    df['BollingerBand_Up_10_2'] = df['Close'].rolling(10).mean() + 2df['Close'].rolling(10).std()

    df['BollingerBand_Down_10_2'] = df['Close'].rolling(10).mean() - 2
df['Close'].rolling(10).std()



    for channel_period in [5,10,20,50,100,200]:

        up_name = "Donchian_Channel_Up_%d" % (channel_period)

        down_name = "Donchian_Channel_Down_%d" % (channel_period)

        

        df[up_name] = df['High'].rolling(channel_period).max()

        df[down_name] = df['Low'].rolling(channel_period).min()



    #create 15 period lag

    for lag in [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]:

        shift = lag

        shifted = df.shift(shift)

        shifted.columns = [str.format("%s_shifted_by_%d" % (column ,shift)) for column in shifted.columns]

        print(df)

        print(df.iloc[-1]['close'])



----------------------------------------------------------------------------------------



Please share any errors you're currently getting. 

 

Hey Thanks,



Also, let me know how to convert Timezone to IST within the code

What should I do to export the output to excel

And if I want to calculate a target price which is a sum multiplication of some of the above arrived data and some numerical values inserted manually. How can I do that



The last, I want a code for:

 

Hello Ashish,



You can check out the examples here on how to convert between timezones:  https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.tz_convert.html



You can use this function to send output to an excel:  https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html



"
And if I want to calculate a target price which is a sum multiplication of some of the above arrived data and some numerical values inserted manually." - can you share an example for this? 













 

See below the example:



Indicator                                                    Current Value    Factor

Close_shifted_by_1                                          1950          101.00

Close_shifted_by_2                                          1949              0.50

SMA_5_shifted_by_1                                        1948        -100.00

Donchian_Channel_Up_5_shifted_by_1          1947             0.04

Open_shifted_by_2                                           1946            0.00


Target Price                                                                         3198


For the timezone, I specifically want to convert to Indian time zone, the formulas are for UTC

Hello Ashish,



In the ibridgepy code we looked at above you had saved each indicator as a column of a dataframe df.



You can create a new dataframe with the same columns as df. You can get the new data frame as below:



factors = pd.DataFrame([101,0.50,-100.0,0.04…],columns=df.columns)



This will create a new dataframe with the same columns as df. 



Now once we have this we can simply multiple both these dataframes to get the target price for each bar/day/minute.



target_price_for_each_bar = df.mul(factor, axis=1)



As a mini-example consider this:



import pandas as pd

df = pd.DataFrame({0: [1,2,3], 1: [4,5,6], 2: [7,8,9] })

factors = pd.Series([-1, 1, -1])

df.mul(factors, axis=1)





----------------------------------------------------------------------------------------------------------

For Indian timezone, you can do something like this:



df.date.tz_localize('US/Pacific').tz_convert('Asia/Kolkata')

where data is the the date column.

For Date, code, df.date.tz_localize('US/Pacific').tz_convert('Asia/Kolkata')



it is showing ,'DataFrame' object has no attribute 'date'



For export to excel formula without date code

df.to_excel(r'D:\Model\Final\df.xlsx')

it is showing, Excel does not support datetimes with timezones. Please ensure that datetimes are timezone unaware before writing to Excel.

Hello Ashish,



df.date.tz_localize('US/Pacific').tz_convert('Asia/Kolkata')



Is an example, please apply the functions to the date column of the data frame in your code. 



Also, before putting the timezone converted to excel you need to remove the timezone info.



You can do so like this: 



df['dates'].apply(lambda x:datetime.replace(x,tzinfo=None))



where df['dates'] should be the datetime column in your data.

 

I tried using this: df['date'] = df.date.tz_localize('US/Pacific').tz_convert('Asia/Kolkata')

, atill does not work

The dat I am getting from Interactive brokers does not have the name of the column containind date and time

 

In that case, you can get date and time using this  https://ibridgepy.com/ibridgepy-documentation/#get_datetime and then convert to the required zone using the above method.