Expected an indent block in comment

时间:2018-02-03 08:32:45

标签: python-3.x

I faced a weird error, "Expected an indent Block" in a comment out line - #______ICHIMOKU SYSTEM's COMPONENTS_____ center = False = see if. I have no idea why. If I delete that line and put anything else in that place, it is starting to show that error on the next part of the code that takes it's place. Please help.

"""
In this project I am going to import data from NSE, learn OOP and
try and learn how to implement various calculations
"""
import datetime
from datetime import date, timedelta
import nsepy as ns
from nsepy.derivatives import get_expiry_date
import sys  # To find out the script name (in argv[0])
import pandas as pd
import matplotlib.pyplot as plt #ploting library
import seaborn
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
from matplotlib.finance import candlestick2_ohlc



class ichimoku():
"""
I have made this class with the intention to calculate Ichimoku components and return them
in form of a pandas dataframe
"""
    def ichical(high_prices,low_prices,close_prices,dates):
        #______ICHIMOKU SYSTEM's COMPONENTS_____ center = False = see if
        #this cause any issues.
        # Tenkan-sen (Conversion Line): (9-period high + 9-period low)/2))
        period9_high = pd.Series.rolling(high_prices, window=9).max()
        period9_low = pd.Series.rolling(low_prices, window=9).min()
        tenkan_sen = (period9_high + period9_low) / 2

        # Kijun-sen (Base Line): (26-period high + 26-period low)/2))
        period26_high = pd.Series.rolling(high_prices, window=26).max()
        period26_low = pd.Series.rolling(low_prices, window=26).min()
        kijun_sen = (period26_high + period26_low) / 2

        # Senkou Span A (Leading Span A): (Conversion Line + Base Line)/2))
        senkou_span_a = ((tenkan_sen + kijun_sen) / 2).shift(26)

        # Senkou Span B (Leading Span B): (52-period high + 52-period low)/2))
        period52_high = pd.Series.rolling(high_prices, window=52).max()
        period52_low = pd.Series.rolling(low_prices, window=52).min()
        senkou_span_b = ((period52_high + period52_low) / 2).shift(26)

        # The most current closing price plotted 26 time periods behind (optional)
        chikou_span = close_prices.shift(-26) 

        #Creating a pandas dataframe based on the components that we have calculated
        df = pd.DataFrame({'tenkan_sen' : tenkan_sen,
                           'kijun_sen' : kijun_sen,
                           'senkou_span_a' : senkou_span_a,
                           'senkou_span_b' : senkou_span_b,
                           'chikou_span' : chikou_span}, index = dates)

        #this command will return the dataframe df
        return df

class user():
"""
I will call this class whenever I want the user's input
"""
    #get_data function will get the market data based on user's requested stock or option
    def get_data():
        while True:
            cs = input("""What type of instrument you want to do the analysis
                    with, Options or Stocks? Enter O or S :""")
            if cs.lower() == 's':
                #this part will get the stock data
                while True:
                    try:
                        us = input('Enter the name of your stock :')
                        us_sd = input('Enter the start date in yyyy-mm-dd :')
                        year, month, day = map(int, us_sd.split("-"))
                        us_sd = datetime.date(year,month,day)
                        data = ns.get_history(symbol=us.upper(), start=us_sd, end=date.today())

                        if data.empty:
                            print('No results, please alter your search and try again')
                            continue
                        break
                    except Exception as e:
                        print('There was an error in your input, please try again :{0}'.format(e))
                break
            elif cs.lower() == 'o':
                #this part will get the option data
                end_date = date.today()
                start_date = end_date - timedelta(60)
                month = end_date.month
                year = end_date.year
                while True:
                    try:
                        ios = input('Stock option or Index option? Enter S/I')

                        if ios.lower() == 's':
                            uo = input('Enter the name of your underlying Stock :')
                            ot = input('Enter option type: CE for call and PE for put :')
                            sp = input('Enter the strike price :')
                            sp = int(sp)

                            stock_opt = ns.get_history(symbol=uo.upper(),
                                                       start=start_date,
                                                       end=end_date,
                                                       index=False,
                                                       option_type=ot,
                                                       strike_price=sp,
                                                       expiry_date=get_expiry_date(year,month))
                            data = stock_opt
                        elif ios.lower() == 'i':
                            uo = input('Enter the name of your underlying Index :')
                            ot = input('Enter option type: CE for call and PE for put :')
                            sp = input('Enter the strike price :')
                            sp = int(sp)

                            index_opt = ns.get_history(symbol=uo.upper(),
                                                       start=start_date,
                                                       end=end_date,
                                                       index=True,
                                                       option_type=ot,
                                                       strike_price=sp,
                                                       expiry_date=get_expiry_date(year,month))
                            data = index_opt
                        else:
                            print('That is not a valid input, please try again')
                            continue

                        if data.empty:
                            print('There was an error processing your request, Please check your inputs and try again')
                            continue
                        break
                    except Exception as e:
                        print('One of your input was invalid, please try again')

                break
            else:
                print('You have entered an invalid input :' + cs + ' Please try again')


        #once we obtain the data we then return it to our main program
        return data


class ohlc():
"""
This class will plot the data sent into it as a candlestick chart.
It should plot the Candlestick chart along with the ichimoku data
format = candlestick2_ochl(ax, opens, closes, highs, lows, width=4, colorup='k', colordown='r', alpha=0.75)
"""
    def plot_chart(cdata,cichi):
        copen = cdata['Open']
        cclose = cdata['Close']
        chigh = cdata['High']
        clow = cdata['Low']
        cvolume = cdata['Volume']
        fig = plt.figure()
        ax1 = plt.subplot2grid((1,1),(0,0))

        #setting the candlestick chart
        candlestick2_ohlc(ax1, copen, cclose, chigh, clow, colorup = 'g', colordown = 'r', alpha=0.80)
        ax1.grid(True)

        #giving names to the x and y axis of the chart
        plt.xlabel('Date')
        plt.ylabel('Price')


        #setting the ichimoku components
        cichi['tenkan_sen'].plot(ax=ax1, color='g',label='Tenkan', lw=2)
        cichi['kijun_sen'].plot(ax=ax1, color='g',label='Kijun', lw=2)

        plt.show()             
#__________________Everything else gets called from here____________________

if __name__ == '__main__':
    #setting start date and end date
    end_date = date.today()
    print(end_date)
    start_date = end_date - timedelta(60)
    #print(start_date)
    month = end_date.month
    year = end_date.year
    #print(year)

##    #get data of NIFTY50 Call option of 11100 strike price
##    nifty_opt = ns.get_history(symbol="NIFTY",
##                        start=start_date,
##                        end=end_date,
##                        index=True,
##                        option_type='CE',
##                        strike_price=11100,
##                        expiry_date=get_expiry_date(year,month))
    #print(nifty_opt.tail())

    #setting datas for calculation Ichimoku's components

##    data = user.get_data()
    data = ns.get_history(symbol='SBIN', start=start_date, end=end_date)

    high_prices = data['High']
    low_prices = data['Low']
    close_prices = data['Close']
    dates = data.index

    ichi = ichimoku.ichical(high_prices,low_prices,close_prices,dates)

    candle = ohlc.plot_chart(data,ichi)

The error in comment out region

The error even if I delete the comment

1 个答案:

答案 0 :(得分:2)

A docstring should be the first statement under whatever it belongs to. Your class docstring is not indented to be a part of the class, hence the odd error you are getting.

As a side note, the first argument of a method is an instance, usually named self.

This works:

"""Module docstring"""

class A:
    """
    Class docstring
    """
    def method(self):
        """
        Method docstring
        """
        ...

This is not valid syntax:

"""Module docstring"""

class A:
"""
Class docstring
"""
    def method(self):
        """
        Method docstring
        """
        ...