Изучение методов фондового рынка с помощью примеров кода на Python

  1. Получение цен на акции.
    Вы можете получить цены на акции с помощью таких API, как Alpha Vantage или Yahoo Finance.

    import yfinance as yf
    
    # Get the stock data
    stock = yf.Ticker("ROBIN")
    stock_data = stock.history(period="1d")
    
    # Print the stock data
    print(stock_data)
  2. Технические индикаторы.
    Технические индикаторы могут дать представление о тенденциях и моделях цен на акции.

    import talib
    
    # Get the closing prices
    close_prices = stock_data["Close"].values
    
    # Calculate the moving average
    ma = talib.SMA(close_prices, timeperiod=10)
    
    # Print the moving average
    print(ma)
  3. Бэктестирование торговой стратегии.
    Вы можете протестировать свои торговые стратегии, используя исторические данные по акциям.

    import backtrader as bt
    
    class MyStrategy(bt.Strategy):
       def __init__(self):
           # Define your trading strategy here
           pass
    
       def next(self):
           # Implement your trading logic here
           pass
    
    # Create a cerebro instance
    cerebro = bt.Cerebro()
    
    # Add the strategy
    cerebro.addstrategy(MyStrategy)
    
    # Add the data feed
    data = bt.feeds.YahooFinanceData(dataname="ROBIN", fromdate=start_date, todate=end_date)
    cerebro.adddata(data)
    
    # Run the backtest
    cerebro.run()
  4. Оптимизация портфеля.
    Вы можете оптимизировать свой портфель акций, используя такие методы, как оптимизация среднего отклонения.

    import numpy as np
    import scipy.optimize as sco
    
    # Define the expected returns and covariance matrix
    returns = np.array([0.1, 0.2, 0.15])
    cov_matrix = np.array([[0.05, 0.03, 0.02], [0.03, 0.08, 0.05], [0.02, 0.05, 0.1]])
    
    # Define the objective function for optimization
    def objective(weights):
       return np.dot(weights, returns) / np.sqrt(np.dot(weights, np.dot(cov_matrix, weights)))
    
    # Define the constraint for the weights
    constraints = [{'type': 'eq', 'fun': lambda x: np.sum(x) - 1}]
    
    # Perform portfolio optimization
    result = sco.minimize(objective, x0=initial_weights, method='SLSQP', constraints=constraints)
    optimized_weights = result.x
    
    # Print the optimized weights
    print(optimized_weights)
  5. Анализ настроений.
    Вы можете выполнить анализ настроений на основе данных социальных сетей, чтобы оценить настроения рынка.

    from textblob import TextBlob
    
    # Define the text to analyze
    text = "I think Robin's stock will go up."
    
    # Perform sentiment analysis
    sentiment = TextBlob(text).sentiment
    
    # Print the sentiment
    print(sentiment.polarity)